【发布时间】:2010-09-29 09:01:11
【问题描述】:
我们的项目前几天已经从 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,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