如何更改TextWriter对象中的编码? [英] How to change encoding in TextWriter object?

查看:70
本文介绍了如何更改TextWriter对象中的编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有xml,我通过API在另一次转储中发送了该xml.我通过XDocument创建它:

I have xml which I send by API in another resurse. I create it by XDocument:

XDocument xDoc = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"),
    new XElement("Entity",new XAttribute("Type", "attribute1"),
        new XElement("Fields",...

当我将其放入请求中时,它已发送而未声明.所以我下一步:

When I put it in the request it has sent without declaration. So I do next:

StringBuilder builder = new StringBuilder();
TextWriter writer = new StringWriter(builder);

using (writer)
{
    xDoc.Save(writer);
}

但是现在TextWriter将xml中的编码更改为utf-16.我需要在utf-8上再次更改它.

But now TextWriter change encoding in xml to utf-16. I need to change it again on utf-8.

推荐答案

这似乎很奇怪,但是如果要在xml中使用utf-8编码输出到string,则似乎必须对StringWriter进行子类化.

This seems odd, but it looks like you have to subclass StringWriter if you want to output to a string with utf-8 encoding in the xml.

public class Program
{
    public static void Main(string[] args)
    {
        XDocument xDoc = new XDocument(
            new XDeclaration("1.0", "utf-8", "yes"),
            new XElement("Entity",new XAttribute("Type", "attribute1")));

        StringBuilder builder = new StringBuilder();
        using (TextWriter writer = new EncodingStringWriter(builder, Encoding.UTF8))
        {
            xDoc.Save(writer);
        }

        Console.WriteLine(builder.ToString());
    }
}

public class EncodingStringWriter : StringWriter
{
    private readonly Encoding _encoding;

    public EncodingStringWriter(StringBuilder builder, Encoding encoding) : base(builder)
    {
        _encoding = encoding;
    }

    public override Encoding Encoding
    {
        get { return _encoding;  }                
    }
}

这篇关于如何更改TextWriter对象中的编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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