【问题标题】:Different behaviors between XmlDocument.LoadXml and XDocument.ParseXmlDocument.LoadXml 和 XDocument.Parse 之间的不同行为
【发布时间】:2010-09-29 09:01:11
【问题描述】:

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

  1. XML 字符串:

    字符串 xml = @"";

  2. XmlDocument.LoadXml 代码和结果:

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

    结果:

  3. 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,String[] args) 在 System.Xml.XmlTextReaderImpl.Throw(Int32 pos,String res,String[] args) 在 System.Xml.XmlTextReaderImpl.ParseNumericCharRefInline(Int32 startPos,布尔扩展,StringBuilder internalSubsetBuilder,Int32& charCount,EntityType& entityType) 在 System.Xml.XmlTextReaderImpl.ParseNumericCharRef(布尔扩展,StringBuilder internalSubsetBuilder,EntityType& entityType) 在 System.Xml.XmlTextReaderImpl.HandleEntityReference(布尔 isInAttributeValue,EntityExpandType expandType,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(字符串文本,LoadOptions 选项) 在 System.Xml.Linq.XDocument.Parse(字符串文本)

似乎“”是无效字符,因此我们将值更改为有效字符,例如“`”那么这两种方法都运行良好。

有没有什么方法可以改变 XDocument.Parse 的行为,以像 XmlDocument.LoadXml 一样忽略属性中的无效字符?

【问题讨论】:

    标签: c# xml linq-to-xml


    【解决方案1】:

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

    阅读这篇文章,他们会给出如何解决该错误的建议。

    【讨论】:

      猜你喜欢
      • 2014-11-01
      • 1970-01-01
      • 2018-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多