Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change encoding in TextWriter object?

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.

like image 401
user1848942 Avatar asked Feb 07 '13 04:02

user1848942


2 Answers

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;  }                
    }
}
like image 56
Mike Zboray Avatar answered Nov 20 '22 06:11

Mike Zboray


Try

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

or

TextWriter ws = new StreamWriter(stream, Encoding.UTF8);
like image 23
abatishchev Avatar answered Nov 20 '22 06:11

abatishchev