【发布时间】:2021-01-11 20:52:21
【问题描述】:
我使用 XmlDocument、XmlElement 等进行了一些 XML 操作。
我将其替换为使用 XDocument、XElement 等的代码,以使其现代化。
但是,元素的某些内部文本包含字符 '\x4'。
使用 XmlDocument.Save() 将其保存为  并且一切正常,即使使用第三方工具也是如此。但是 XDocument.Save() 抛出
System.ArgumentException: '', hexadecimal value 0x04, is an invalid character.
+ System.Xml.XmlUtf8RawTextWriter.InvalidXmlChar(int, System.Byte*, bool)
+ System.Xml.XmlUtf8RawTextWriter.WriteElementTextBlock(System.Char*, System.Char*)
+ System.Xml.XmlUtf8RawTextWriter.WriteString(string)
+ System.Xml.XmlUtf8RawTextWriterIndent.WriteString(string)
+ System.Xml.XmlWellFormedWriter.WriteString(string)
+ System.Xml.Linq.ElementWriter.WriteElement(System.Xml.Linq.XElement)
+ System.Xml.Linq.XElement.WriteTo(System.Xml.XmlWriter)
+ System.Xml.Linq.XContainer.WriteContentTo(System.Xml.XmlWriter)
+ System.Xml.Linq.XDocument.WriteTo(System.Xml.XmlWriter)
+ System.Xml.Linq.XDocument.Save(string, System.Xml.Linq.SaveOptions)
+ System.Xml.Linq.XDocument.Save(string)
我暂时使用了 XmlConvert.EncodeName(),但这会将其转换为 _x0004_,除非使用 XmlConvert.DecodeName() 解码,否则无法正确读取。
可以实现之前的保存功能吗?
最小步骤:
//ok
Console.WriteLine(new XDocument(new XElement("test","aa")).ToString());
//System.ArgumentException: '', hexadecimal value 0x04, is an invalid character.
Console.WriteLine(new XDocument(new XElement("test","aa \x4")).ToString());
编辑: 搜索 .NET 源,我发现之前的正确行为可能是由私有 XmlTextEncoder.WriteCharEntityImpl(string) 完成的。但是,这个类似乎没有记录,我无法想象我可以如何利用。
【问题讨论】:
-
@Selvin 感谢您的编辑
-
实际上是disallowed by XML 1.0,所以XDocument.Save()是在做正确的事情。如果您需要在文档中包含该字符,则应考虑对其进行 base64 编码(认识到 XML 并非旨在直接携带二进制文件)或更新到 XML 1.1(允许除 U+0 之外的所有内容——但这可能不是如果您需要指定 0 并且几乎没有任何东西支持 XML 1.1),则可以选择此选项。
标签: c# linq-to-xml xmldocument