的XDocument字符串:如何省略编码的声明? [英] XDocument to string: How to omit encoding in declaration?
问题描述
我正在写一个新空房禁地企业XML API的包装。我有一个XDocument,我需要转成字符串。由于这样的事实,他们的XML解析器是如此挑剔,它甚至不能处理XML节点之间的空白,文档声明必须精确:
I'm writing a wrapper for a braindead enterprise XML API. I have an XDocument that I need to turn into a string. Due to the fact that their XML parser is so finicky that it cannot even handle whitespace between XML nodes, the document declaration MUST be EXACTLY:
<?xml version="1.0"?>
不过,XDocument.Save()方法的总是在声明中补充道编码属性:
However, the XDocument.Save() method always adds an encoding attribute in that declaration:
<?xml version="1.0" encoding="utf-16"?>
随着过去一小时的谷歌和堆栈寻找生成XML字符串的最佳方式度过的,我能做的最好的是:
With the past hour spent on Google and Stack looking for the best way to generate the XML string, the best I can do is:
string result = xmlStringBuilder.ToString().Replace(@"encoding=""utf-16"", string.Empty));
我试过
xdoc.Declaration = new XDeclaration("1.0", null, null);
和,它在我想要的方式设置在XDocument申报成功;然而,当我调用Save()方法,编码属性被神奇地后仰在那里,无论我走什么路线(使用的TextWriter,加入XmlWriterSettings,等等)。
and that does succeed at setting the declaration in the XDocument the way I want it; however, when I call the Save() method, the encoding attribute gets magically thrown back in there, no matter what route I go (using TextWriter, adding XmlWriterSettings, etc.).
有没有人有更好的方式来做到这一点,或者是我的code永远注定要在可怕的串上述评论咆哮更换一个段落?
Does anyone have a better way to do this, or is my code forever doomed to have a paragraph of ranting in comments above the hideous string replace?
推荐答案
好接收端应该是固定的,如果你想创建的字符串使用XML解析器和不是使用XML语法,但使用.NET打破XML声明为您发布它下面的方法对我的作品:
Well the receiving end should be fixed to use an XML parser and not something that breaks with XML syntax but with .NET if you want to create a string with the XML declaration as you posted it the following approach works for me:
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);
输出
<?xml version="1.0"?>
<root>test</root>
这篇关于的XDocument字符串:如何省略编码的声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!