我使用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(字符串)完成的。然而,这个类似乎没有文档化,我无法想象如何利用它。
发布于 2020-09-26 10:45:50
我找到了一种可以接受的方式来做我想做的事情,通过使用一个XmlTextWriter来保存,所以我把它作为我自己问题的答案。但是,如果只有LINQ到XML类有解决方案的话,我更愿意这样做。
using System;
using System.Xml;
using System.Xml.Linq;
public class Program
{
public static void Main()
{
var xdoc=new XDocument(new XElement("Params", new XElement("test","aa1 \x4")));
using (var xw = new XmlTextWriter(Console.Out)
{
Formatting=Formatting.Indented
} )
xdoc.WriteTo(xw);
}
}https://stackoverflow.com/questions/64065477
复制相似问题