C# XmlDocument.Save()与XDocument.Save()的比较
我使用XmlDocument、XmlElement等进行了一些XML操作。 我用使用XDocument、XElement等实现现代化的代码替换了它。 但是,元素的某些内部文本包含字符C# XmlDocument.Save()与XDocument.Save()的比较,c#,linq-to-xml,xmldocument,C#,Linq To Xml,Xmldocument,我使用XmlDocument、XmlElement等进行了一些XML操作。 我用使用XDocument、XElement等实现现代化的代码替换了它。 但是,元素的某些内部文本包含字符'\x4'。 使用XmlDocument.Save()将其保存为和#x4并且一切都正常工作,即使使用第三方工具也是如此。但是XDocument.Save()抛出 我暂时使用了XmlConvert.EncodeName(),但这会将其转换为\u x0004\u,除非使用XmlConvert.DecodeName()进行
'\x4'
。
使用XmlDocument.Save()将其保存为和#x4代码>并且一切都正常工作,即使使用第三方工具也是如此。但是XDocument.Save()抛出
我暂时使用了XmlConvert.EncodeName(),但这会将其转换为\u x0004\u
,除非使用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(字符串)完成的。然而,这个类似乎没有文档记录,我无法想象如何利用它。我找到了一种可以接受的方法来做我想做的事情,使用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);
}
}
@Selvin感谢您的编辑
实际上是,因此XDocument.Save()
做的事情是正确的。如果您需要在文档中包含该字符,则应该考虑Base64编码(识别XML不是直接携带二进制)或更新到XML 1.1(它允许除U+0以外的所有内容,但如果您需要指定0,并且几乎没有支持XML 1.1),那么这可能不是您的选择。
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);
}
}