你好,感谢你们的帮助,我一直在推进这项任务。 程序必须做两件事,首先读取目录中的每个 xml 文件,并显示它们正在处理/告诉其中一个作为错误,然后插入到我拥有的 sql 表中。 首先显示我的程序.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using system.xml;
using System.Data;
using system.xml.Serialization;
namespace XMLReaderConsoleAPP1
{
class Program
{
public static void Main()
{
Dataaccess da = new Dataaccess();
XmlSerializer serializer = new XmlSerializer(typeof(ImportSession));
MemoryStream stream = new MemoryStream();
using (StreamWriter sw = new StreamWriter(stream)){
sw.Write(INPUT);
sw.Flush();
stream.Position = 0;
}
try
{
foreach(string file in Directory.EnumerateFiles(@"C:\XMLFiles","*.xml"))
{
ProcessFile(file);
}
//var path = @"C:\XMLFiles";
//DirectoryInfo di = new DirectoryInfo(path);
//foreach (var file in Directory.GetFiles(path,"*.xml"))
//{
// ProcessFile(file);
//}
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine("Erro: {0}",ex.Message);
return;
}
void ProcessFile(string Filename)
{
bool temErro = false;
Console.WriteLine("A processar xml: " + Filename);
XmlDocument xml = new XmlDocument();
xml.Load(Filename);
//XmlNodeList xnLista = xml.SelectNodes(@"//Pages/Page");
//Console.WriteLine($"Selected {xnLista.Count} nodes");
XmlNodeList xnLista3 = xml.SelectNodes(@"//ImportSession/Batches");
XmlNodeList xnLista2 =
xml.SelectNodes(@"//ImportSession/Batches/Batch/Documents/Document/Pages/Page");
foreach (XmlNode xn in xnLista2)
{
//Console.WriteLine($"{++i} {xn.Name}: {xn.Attributes["ImportFileName"].Value}");
string processed = "@//Batch[Processed]";
//Console.WriteLine($"{++j} {xn.Name}: {xn.Attributes["Value"].Value}");
string BatchClassname = xn.Attributes["BatchClassname"]?.Value;
string BatchName = xn.Attributes["Name"]?.Value;
string BatchDescription = xn.Attributes["Description"]?.Value;
//string process = xn.Attributes["Processed"]?.Value;
string error = xn.Attributes["ErrorMessage"]?.Value;
string errorImagePath = xn.Attributes["ErrorCode"]?.Value;
if (!string.IsnullOrEmpty(processed)) //xml já foi processado
{
if (!string.IsnullOrEmpty(error))
{
string page = xn.Attributes["ImportFileName"].Value;
Console.WriteLine("Página com erro: " + page);
temErro = true;
ImportSession session = (ImportSession)serializer.Deserialize(stream);
foreach(Batch batch in session.Batches)
{
foreach(Document doc in batch.Documents)
{
foreach(Page page in doc.Pages)
{
da.SP_Insert("BatchName='{0}',BatchDescription='{1}',BatchClassname='{2}'," +
"ImportFileName={3},ErrorMessage={4},HasError={5},Processed={6}",batch.Name,batch.Description,batch.BatchClassname,page.ImportFileName,page.ErrorMessage,page.HasError,batch.Processed);
}
}
}
}
}
}
if (temErro)
Console.WriteLine("Ficheiro com erro: " + Filename);
else
Console.WriteLine("Ficheiro processado: " + Filename);
//Console.WriteLine(Filename);
}
}
}
public class ImportSession
{
public Batch[] Batches { get; set; }
}
public class Batch
{
[XmlAttribute]
public string Name { get; set; }
[XmlAttribute]
public string Description { get; set; }
[XmlAttribute]
public string BatchClassname { get; set; }
[XmlAttribute]
public bool Processed { get; set; }
public Document[] Documents { get; set; }
}
public class Document
{
[XmlAttribute]
public string FormTypeName { get; set; }
public IndexField[] IndexFields { get; set; }
public Page[] Pages { get; set; }
}
public class IndexField
{
[XmlAttribute]
public string Name { get; set; }
[XmlAttribute]
public string Value { get; set; }
}
public class Page
{
[XmlAttribute]
public string ImportFileName { get; set; }
[XmlAttribute]
public string ErrorCode { get; set; }
[XmlAttribute]
public string ErrorMessage { get; set; }
[XmlIgnore]
public bool HasError => !string.IsnullOrWhiteSpace(ErrorMessage);
}
}
我真的不明白为什么它甚至没有运行,所以除了向你们展示程序之外,我无法提供太多输入。 现在有我的 dataaccess.cs 文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
namespace XMLReaderConsoleAPP1
{
class Dataaccess
{
SqlConnection connection = null;
public Dataaccess()
{
connection = new SqlConnection(@"Persist Security Info=False;Integrated Security=true; Initial Catalog=Teste;Data Source=Teste;Server=localhost\sqlexpress");
}
private void ManageConnectionState()
{
if (connection == null || connection.ConnectionString.Equals(""))
{
connection = new SqlConnection(@"Persist Security Info = False; Integrated Security = true; Initial Catalog = Teste; Data Source = Teste; Server = localhost\sqlexpress");
connection.Open();
}
else
if (connection.State.Equals(ConnectionState.Closed))
{
connection.Open();
}
else
{
connection.Dispose();
connection.Close();
}
}
#region Insert
public void SP_Insert(string XMLPath,string XMLName,string BatchClassname,string BatchName,string BatchDescription,bool Error,string ErrorImagePath,string Done)
{
try
{
ManageConnectionState();
SqlCommand command = new SqlCommand("Sp_Insert",connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@XMLPath",SqlDbType.NText).Value = XMLPath;
command.Parameters.Add("@XMLName",SqlDbType.NText).Value = XMLName;
command.Parameters.Add("@BatchClassname",SqlDbType.NText).Value= BatchClassname;
command.Parameters.Add("@BatchName",SqlDbType.NText ).Value = BatchName;
command.Parameters.Add("@BatchDescription",SqlDbType.NText ).Value = BatchDescription;
command.Parameters.Add("@Error",SqlDbType.Bit).Value = Error;
command.Parameters.Add("@ErrorImagePath",SqlDbType.NText).Value = ErrorImagePath;
command.Parameters.Add("@Done",SqlDbType.NText ).Value=Done;
command.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine("Erro: " + ex.Message);
}
finally
{
ManageConnectionState();
connection.Close();
}
}
#endregion
}
}
最后在数据库中显示我的 StoredProcedure
USE [Teste]
GO
/****** Object: StoredProcedure [dbo].[SP_Insert] Script Date: 22/01/2021 09:32:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[SP_Insert]
@XMLPath nvarchar(250),@XMLName nvarchar(250),@BatchClassname nvarchar(250),@BatchName nvarchar(250),@BatchDescription nvarchar(250),@Error bit,@ErrorImagePath nvarchar(250),@Done bit
AS
BEGIN
Insert into T_XMLFiles (XMLPath,XMLName,BatchClassname,BatchName,BatchDescription,Error,ErrorImagePath,Done)
Values(@XMLPath,@XMLName,@BatchClassname,@BatchName,@BatchDescription,@Error,@ErrorImagePath,@Done)
END
希望这次我能最终完成这项工作,提前感谢大家的帮助,但正如我所说,我不知道为什么它不起作用,因为它甚至没有给出错误。