为什么Xdocument给我一个utf16声明? [英] why does the Xdocument give me a utf16 declaration?

查看:31
本文介绍了为什么Xdocument给我一个utf16声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个像这样的XDocument:

i'm creating a XDocument like this:

XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"));

当我这样保存文档时( doc.Save(@"c:\ tijd \ file2.xml"); ),我得到了:

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"?>

没关系.

但是我想将内容作为xml返回,并且我发现了以下代码:

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());

此代码有效,但字符串's'以此开头:

this code works, but then the string 's' starts with this:

<?xml version="1.0" encoding="utf-16" standalone="yes"?>

所以它从utf8更改为utf16,这不是我想要的,因为现在我无法在Internet Explorer中阅读它.

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?

推荐答案

StringWriter 自我宣传为使用UTF-16.修复起来很容易:

StringWriter advertises itself as using UTF-16. It's easy to fix though:

public class Utf8StringWriter : StringWriter
{
    public override Encoding Encoding { get { return Encoding.UTF8; } }
}

在您的特定情况下就足够了.更加全面的实现会:

That should be enough in your particular case. A rather more well-rounded implementation would:

  • 具有与 StringWriter
  • 中的构造函数匹配的构造函数
  • 也允许在构造函数中指定编码

这篇关于为什么Xdocument给我一个utf16声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆