How to change encoding in TextWriter object?

2020-06-04 05:52发布

问题:

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

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

回答1:

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;  }                
    }
}


回答2:

Try

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

or

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