【问题标题】:System.InvalidOperationException: 'There is an error in the XML document (1, 1).'System.InvalidOperationException: 'XML 文档 (1, 1) 中存在错误。'
【发布时间】: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


【解决方案1】:

这个:

        MemoryStream stream = new MemoryStream();
        using (StreamWriter sw = new StreamWriter(stream))
        {
            sw.Write(stream);
            sw.Flush();
            stream.Position = 0;

基本上没有意义。无论stream 的内容是什么:不是这个。问问自己:

stream 的含义是什么?

目前它包含......它自己,有点,但不是真的?

如果您打算将流作为文件内容:只需使用File.OpenRead

【讨论】:

  • 该部分将用于通过 sp 插入数据库
  • 嗨,Marc,对不起:我想这是我的错。我在小提琴中向 OP 展示了一些示例,我们显然无法从文件中加载。所以我从文字创建了一个流。这似乎是一个残留物。
  • @TiagoSilva 怎么样?这就是您在serializer.Deserialize(stream)从中读取 的流;所以:从哪里获取内容?
  • @Fildor 如果是任何人的错,我就是那个什么都做不了的人,对不起你们俩
  • @TiagoSilva 用于上下文:现在,流包含字符串:"System.IO.MemoryStream" - 不多也不少;这可能不是你想要的
【解决方案2】:

我认为这是基于对该主题先前问题的答案的误解。

这应该使它工作但是请记住,它绝不是生产就绪

public static void Main()
{
    XmlSerializer serializer = new XmlSerializer(typeof(ImportSession));
    foreach (string filename in Directory.EnumerateFiles(@"C:\XMLFiles", "*.xml"))
        {
            ProcessFile(filename, serializer);
        }
    Console.ReadKey();
}

private static void ProcessFile(string Filename, XmlSerializer serializer)
{
    bool temErro = false;
    Console.WriteLine("A processar xml: " + Filename);

    using (var file = File.OpenRead(Filename)) { 
        var session = (ImportSession)serializer.Deserialize(file);

// from here on the rest of your code ...

最小化保持文件打开的代码:

    ImportSession session;
    using (var file = File.OpenRead(Filename)) 
    { 
            session = (ImportSession)serializer.Deserialize(file);
    } 
    // file will be closed by disposal of FileStream using this notation

    // rest of code

附录

if (!string.IsNullOrEmpty(batch.Processed.ToString()))
{   // Will ALWAYS be entered!
    if (!string.IsNullOrEmpty(page.HasError.ToString()))
    {   // Will ALWAYS be entered!
        string Import = page.ImportFileName;
        Console.WriteLine("Página com erro:" + Import);
        temErro = true;
    }
}

让我们看一下: !string.IsNullOrEmpty(page.HasError.ToString()) 总是正确的。为什么?

page.HasError 的类型为 bool。所以,page.HasError.ToString() “将此实例的值转换为其等效的字符串表示形式(“True”或“False”)。”

所以,它永远不会是 nullempty。因此,string.IsNullOrEmpty 将始终为 false,!string.IsNullOrEmpty 因此始终为 true。

如果要检查布尔值,只需执行if( page.HasError ) => "Page has an error"

【讨论】:

  • 它在 processFile 中的 stream 和 xmlSerializer 以及 main 不能调用 processfile 中的 foreach 循环上给出错误
  • 重要:文件仍需要关闭,最好使用using
  • 什么文件?能具体点吗?
  • @TiagoSilva 很好:using (var file = File.OpenRead(FileName)) { var session = (ImportSession)serializer.Deserialize(file); // ... }
  • Niceeee 它的工作哈哈现在是时候尝试插入数据库 @Fildor
猜你喜欢
  • 1970-01-01
  • 2014-07-11
  • 1970-01-01
  • 2021-04-05
  • 1970-01-01
  • 1970-01-01
  • 2016-05-12
  • 2011-12-18
  • 2021-11-08
相关资源
最近更新 更多