7

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.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
user1848942
  • 355
  • 1
  • 5
  • 21

2 Answers2

14

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;  }                
    }
}
Mike Zboray
  • 39,828
  • 3
  • 90
  • 122
4

Try

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

or

TextWriter ws = new StreamWriter(stream, Encoding.UTF8);
abatishchev
  • 98,240
  • 88
  • 296
  • 433
  • 1
    or `Encoding.GetEncoding(1256)` if you need a specific code page (1256 is Arabic) – BlueChippy Feb 07 '13 at 04:19
  • `StreamWriter` seems like the obvious solution, yes; it is, after all, the specific encoding-customizable implementation of `TextWriter`, the type expected by `XDocument.Save`. Even for just going back to String (but getting the XML declaration right) I just use this, on a `MemoryStream`. – Nyerguds Jan 14 '15 at 13:14