c# - System.InvalidOperationException: 'XML 文档 (1, 1) 中存在错误。'
问题描述
这个错误出现在我的代码中,还有第二个如下:
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);
}
这个应用程序现在只是试图读取所有文件并指出需要在控制台中显示的一些部分并且它正在这样做,但我被建议在这里更改为这个面向对象和内存流。
解决方案
这个:
MemoryStream stream = new MemoryStream();
using (StreamWriter sw = new StreamWriter(stream))
{
sw.Write(stream);
sw.Flush();
stream.Position = 0;
基本上是没有意义的。不管它的内容stream
是什么:不是这个。问你自己:
包含什么
stream
?
目前它包含……它自己,有点,但不是真的?
如果您打算将流作为文件内容:只需使用File.OpenRead
推荐阅读
- python - 如何用给定的索引多次对称地覆盖二维 numpy?
- c - 在 C 中获取 mod 10 的最快方法
- python - 如何通过使用多个文件在 Python 中正确使用多处理?
- python - Python CSV 删除表示为的新行
- php - 转换成十进制后的密码比较
- python - 使用 Pycharm 安装 Pillow 失败
- javascript - 如何从firebase数据库中获取密钥
- python - 将字典传递给函数而不更改先前处理的值
- reactjs - 我的 API laravel 在我的 reactjs 上运行时不起作用
- java - 如何比较firestore中的日期