7

我有 xml,我通过 API 在另一个资源中发送。我通过 XDocument 创建它:

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

当我将其放入请求中时,它已在未声明的情况下发送。所以我接下来做:

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

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

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

4

2 回答 2

13

这看起来很奇怪,但StringWriter如果你想输出到stringxml 中的 utf-8 编码,你似乎必须进行子类化。

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;  }                
    }
}
于 2013-02-07T04:32:55.333 回答
4

尝试

TextWriter ws = new StreamWriter(path, true, Encoding.UTF8);

或者

TextWriter ws = new StreamWriter(stream, Encoding.UTF8);
于 2013-02-07T04:06:22.910 回答