C# XmlDocument.LoadXml和XDocument.Parse之间的不同行为

C# XmlDocument.LoadXml和XDocument.Parse之间的不同行为,c#,xml,linq-to-xml,C#,Xml,Linq To Xml,几天前,我们的项目已从XmlDocument转换为使用XDocument,但我们在使用XDocument.Parse处理属性值中的XML实体时发现了一个奇怪的行为,示例代码如下: XML字符串: 字符串xml=@ XmlDocument.LoadXml代码和结果: XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(xml); Console.WriteLine(xmlDocument.Oute

几天前,我们的项目已从XmlDocument转换为使用XDocument,但我们在使用XDocument.Parse处理属性值中的XML实体时发现了一个奇怪的行为,示例代码如下:

  • XML字符串:

    字符串xml=@

  • XmlDocument.LoadXml代码和结果:

        XmlDocument xmlDocument = new XmlDocument();
        xmlDocument.LoadXml(xml);
        Console.WriteLine(xmlDocument.OuterXml);
    
    结果:

  • XDocument.Parse代码和异常:

        XDocument xDocument = XDocument.Parse(xml);
        Console.WriteLine(xDocument.ToString());
    
    例外情况:

    System.Xml.dll中首次出现类型为“System.Xml.XmlException”的异常 十六进制值0x00为无效字符。第1行,位置18。 位于System.Xml.XmlTextReaderImpl.Throw(异常e) 位于System.Xml.XmlTextReaderImpl.Throw(字符串res,字符串[]args) 位于System.Xml.XmlTextReaderImpl.Throw(Int32 pos,String res,String[]args) 位于System.Xml.XmlTextReaderImpl.ParseNumericCharRefInline(Int32 startPos、Boolean expand、StringBuilder internalSubsetBuilder、Int32&charCount、EntityType&EntityType) 位于System.Xml.XmlTextReaderImpl.ParseNumericCharRef(布尔展开、StringBuilder internalSubsetBuilder、EntityType和EntityType) 位于System.Xml.XmlTextReaderImpl.HandleEntityReference(布尔值为isInAttributeValue、EntityExpandType、Int32和charRefEndPos) 在System.Xml.XmlTextReaderImpl.ParseAttributeValueSlow(Int32 curPos,Char quoteChar,NodeData attr) 位于System.Xml.XmlTextReaderImpl.ParseAttributes()处 位于System.Xml.XmlTextReaderImpl.ParseElement()处 位于System.Xml.XmlTextReaderImpl.ParseDocumentContent()处 位于System.Xml.XmlTextReaderImpl.Read()处 位于System.Xml.Linq.XDocument.Load(XmlReader阅读器,LoadOptions) 位于System.Xml.Linq.XDocument.Parse(字符串文本,加载选项) 位于System.Xml.Linq.XDocument.Parse(字符串文本)

  • 似乎“�;”是一个无效字符,因此我们将该值更改为一个有效字符,如“`;”,然后这两种方法都很有效

    是否有任何方法可以更改XDocument.Parse行为以忽略属性中的无效字符,如XmlDocument.LoadXml?

    根据值�;实际上是无效的。我亲身体验过,XDocument类遵循的XML标准比XmlDocument严格得多(我认为这是一件好事)

    读了这篇文章,他们给出了如何避免错误的建议