为什么 Xdocument 给我一个 utf16 声明?
我正在创建这样的 XDocument:
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"));
当我像这样保存文档时 (doc.Save(@"c:\tijd\file2.xml");
) ,我得到这个:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
这是可以的。
但我想将内容返回为xml,我发现了以下代码:
var wr = new StringWriter();
doc.Save(wr);
string s = (wr.GetStringBuilder().ToString());
此代码有效,但字符串's'以此开头:
<?xml version="1.0" encoding="utf-16" standalone="yes"?>
所以它从utf8更改为utf16,这不是我想要的,因为现在我无法在 Internet Explorer 中阅读。
有没有办法阻止这种行为?
i'm creating a XDocument like this:
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"));
when i save the document like this (doc.Save(@"c:\tijd\file2.xml");
) , i get this:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
which is ok.
but i want to return the content as xml, and i found the following code:
var wr = new StringWriter();
doc.Save(wr);
string s = (wr.GetStringBuilder().ToString());
this code works, but then the string 's' starts with this:
<?xml version="1.0" encoding="utf-16" standalone="yes"?>
so it changed from utf8 to utf16, and that's not what i want, because now i can't read it in internet explorer.
Is there a way to prevent this behaviour?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
StringWriter
宣传自己使用 UTF-16。但这很容易修复:对于您的特定情况来说这应该足够了。一个更全面的实现将:
StringWriter
中的构造函数相匹配StringWriter
advertises itself as using UTF-16. It's easy to fix though:That should be enough in your particular case. A rather more well-rounded implementation would:
StringWriter
使用继承的非常好的答案,只需记住覆盖初始值设定项
Very good answer using inheritance, just remember to override the initializer
您需要将 StreamWriter.Encoding 设置为使用 UTF-8 而不是 Unicode (UTF-16)
因为它不是 StreamWriter,所以这个答案只留给后代。
You will need to set the
StreamWriter.Encoding
to use UTF-8 instead of Unicode (UTF-16)Seeing as it's not a StreamWriter this answer is only left for posterity.