XDocument to string:如何在声明中省略编码?

我正在为braindead企业XML API编写一个包装器。 我有一个XDocument,我需要变成一个字符串。 由于他们的XML解析器非常挑剔,甚至无法处理XML节点之间的空白,因此文档声明必须完全正确:

 

但是,XDocument.Save()方法始终在该声明中添加一个encoding属性:

  

由于过去一小时花在Google和Stack上寻找生成XML字符串的最佳方法,我能做的最好的事情是:

 string result = xmlStringBuilder.ToString().Replace(@"encoding=""utf-16"", string.Empty)); 

我试过了

 xdoc.Declaration = new XDeclaration("1.0", null, null); 

这确实成功地按照我想要的方式在XDocument中设置声明; 但是,当我调用Save()方法时,无论我走哪条路线(使用TextWriter,添加XmlWriterSettings等),编码属性都会被神奇地抛回其中。

有没有人有更好的方法来做到这一点,或者我的代码永远注定在一个可怕的字符串替换上面的注释中有一段咆哮?

那么接收端应该被修复以使用XML解析器,而不是使用XML语法,但如果你想在发布时使用XML声明创建一个字符串,那么以下方法对我有用:

 public class MyStringWriter : StringWriter { public override Encoding Encoding { get { return null; } } } 

然后

  XDocument doc = new XDocument( new XDeclaration("1.0", null, null), new XElement("root", "test") ); string xml; using (StringWriter msw = new MyStringWriter()) { doc.Save(msw); xml = msw.ToString(); } Console.WriteLine(xml); 

输出

  test