XDocument 到字符串:如何在声明中省略编码?
我正在为一个脑残的企业 XML API 编写一个包装器。我有一个 XDocument,需要将其转换为字符串。由于他们的 XML 解析器非常挑剔,甚至无法处理 XML 节点之间的空格,因此文档声明必须准确无误:
<?xml version="1.0"?>
但是,XDocument.Save() 方法总是在该声明:
<?xml version="1.0" encoding="utf-16"?>
过去一个小时在 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 等)。
有没有人有更好的方法来做到这一点,或者我的代码永远注定在可怕的字符串替换上方的注释中会有一段咆哮?
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"?>
However, the XDocument.Save() method always adds an encoding attribute in that declaration:
<?xml version="1.0" encoding="utf-16"?>
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));
I've tried
xdoc.Declaration = new XDeclaration("1.0", null, null);
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.).
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
那么接收端应该修复为使用 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:
and then
outputs