【发布时间】:2021-04-29 05:58:49
【问题描述】:
这个错误出现在我的代码中,还有第二个如下:
XmlException:根级别的现有数据无效。第 1 行,位置 1
我检查了第二个文件,说文件有错误,因为我的 XMLFiles 目录中有 5 个文件。
public static void Main()
{
XmlSerializer serializer = new XmlSerializer(typeof(ImportSession));
MemoryStream stream = new MemoryStream();
using (StreamWriter sw = new StreamWriter(stream))
{
sw.Write(stream);
sw.Flush();
stream.Position = 0;
}
Console.ReadKey();
foreach (string filename in Directory.EnumerateFiles(@"C:\XMLFiles", "*.xml"))
{
ProcessFile(filename, stream, serializer);
}
void ProcessFile(string Filename, MemoryStream stream, XmlSerializer serializer)
{
bool temErro = false;
Console.WriteLine("A processar xml: " + Filename);
XmlDocument xml = new XmlDocument();
xml.Load(Filename);
ImportSession session = (ImportSession)serializer.Deserialize(stream);
foreach (Batch batch in session.Batches)
{
foreach (Document doc in batch.Documents)
{
foreach (Page page in doc.Pages)
{
if (!string.IsNullOrEmpty(batch.Processed.ToString()))
{
if (!string.IsNullOrEmpty(page.HasError.ToString()))
{
string Import = page.ImportFileName;
Console.WriteLine("Página com erro:" + Import);
temErro = true;
}
}
}
}
}
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);
}
这个应用程序现在只是试图读取所有文件并指出一些需要在控制台中显示的部分,它正在这样做,但我被建议在这里更改为这个面向对象和内存流。
【问题讨论】:
-
错误在xml中。发布它。
-
@Fildor 有 5 个 xml 文件,这个应用程序将用于每小时至少读取 100 个文件,它们都来自另一个不会给出错误的应用程序,它在文件中给出的错误是我需要在应用中显示的那些消息
-
您不需要 StreamWriter 和 MemoryStream。我在 Fiddle 中有那些来加载文字 XML,因为我们无法从 dotnetfiddle 中的文件加载。
-
我在这里发一个,但我不能发每个文件,它不会很好,对吧?你确定这会是 xml 文件的错误吗?
-
“说文件有错误,但没有任何文件”我将信任这里的库;失败时为什么不记录xml。您可能会惊讶地发现,事实并非如此
标签: c# xml serialization