我们的项目前几天已经从XmlDocument转为使用XDocument,但是我们在使用XDocument.Parse处理属性值中的XML实体时发现了一个奇怪的行为,示例代码如下:
XML 字符串:
string 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());
异常(exception):
System.Xml.dll 中发生类型为“System.Xml.XmlException”的第一次机会异常 '.',十六进制值 0x00,是无效字符。第 1 行,位置 18。 在 System.Xml.XmlTextReaderImpl.Throw(异常 e) 在 System.Xml.XmlTextReaderImpl.Throw(String res, String[] args) 在 System.Xml.XmlTextReaderImpl.Throw(Int32 pos,String res,String [] args) 在 System.Xml.XmlTextReaderImpl.ParseNumericCharRefInline(Int32 startPos、 bool 扩展、StringBuilder internalSubsetBuilder、Int32& charCount、EntityType& entityType) 在 System.Xml.XmlTextReaderImpl.ParseNumericCharRef( bool 扩展,StringBuilder internalSubsetBuilder,EntityType 和实体类型) 在 System.Xml.XmlTextReaderImpl.HandleEntityReference( bool 值 isInAttributeValue、EntityExpandType expandType、Int32& charRefEndPos) 在 System.Xml.XmlTextReaderImpl.ParseAttributeValueSlow(Int32 curPos、Char quoteChar、NodeData 属性) 在 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(字符串文本)
似乎“”是无效字符,所以我们将值更改为有效字符,例如“`”那么这两种方法都很有效。
有没有什么方法可以像 XmlDocument.LoadXml 那样改变 XDocument.Parse 的行为来忽略属性中的无效字符?
最佳答案
根据 this arctice值 � 实际上是无效的。我亲 body 验过 XDocument 类遵循比 XmlDocument 严格得多的 XML 标准(我认为这是一件好事)。
阅读这篇文章,他们给出了如何解决该错误的建议。
关于c# - XmlDocument.LoadXml 和 XDocument.Parse 之间的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3820148/