Michel
Michel

Reputation: 23615

why does the Xdocument give me a utf16 declaration?

i'm creating a XDocument like this:

XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"));

when i save the document like this (doc.Save(@"c:\tijd\file2.xml");) , i get this:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>

which is ok.

but i want to return the content as xml, and i found the following code:

 var wr = new StringWriter(); 
            doc.Save(wr); 
            string s = (wr.GetStringBuilder().ToString());

this code works, but then the string 's' starts with this:

<?xml version="1.0" encoding="utf-16" standalone="yes"?>

so it changed from utf8 to utf16, and that's not what i want, because now i can't read it in internet explorer.

Is there a way to prevent this behaviour?

Upvotes: 33

Views: 7802

Answers (3)

Sebastian Castaldi
Sebastian Castaldi

Reputation: 9004

Very good answer using inheritance, just remember to override the initializer

   public class Utf8StringWriter : StringWriter
    {
        public Utf8StringWriter(StringBuilder sb) : base (sb)
        {
        }
        public override Encoding Encoding { get { return Encoding.UTF8; } }
    }

Upvotes: 3

msarchet
msarchet

Reputation: 15242

You will need to set the StreamWriter.Encoding to use UTF-8 instead of Unicode (UTF-16)

Seeing as it's not a StreamWriter this answer is only left for posterity.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500514

StringWriter advertises itself as using UTF-16. It's easy to fix though:

public class Utf8StringWriter : StringWriter
{
    public override Encoding Encoding { get { return Encoding.UTF8; } }
}

That should be enough in your particular case. A rather more well-rounded implementation would:

  • Have constructors matching those in StringWriter
  • Allow the encoding to be specified in the constructor too

Upvotes: 43

Related Questions