ib11
ib11

Reputation: 2568

XmlWriter Encoding in C#

I have an XmlDocument and I am saving it with an XmlWriter, using this post. Despite setting the Encoding to Utf-8 and the file getting saved with Utf-8 encoding in fact, the xml declaration in the file has the "utf-16" as the value of the encoding attribute.

I can't see where is the error in my code:

StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings
{
    Encoding=Encoding.UTF8
};
using (XmlWriter writer = XmlWriter.Create(sb, settings))
{
    xDoc.Save(writer);
}
using (
    StreamWriter sw = new StreamWriter(
        new FileStream(strXmlName, FileMode.Create, FileAccess.Write),
        Encoding.UTF8
    )
)
{
    sw.Write(sb.ToString());
}

Upvotes: 1

Views: 2590

Answers (1)

Charles Mager
Charles Mager

Reputation: 26213

The reason for this is covered in the question @dbc links to in the comments: The overload of XmlWriter.Create that accepts a StringBuilder will create a StringWriter, which has its encoding set to UTF-16.

However, in this case it's not clear why you're using a StringBuilder when your goal is to write to a file. You could create an XmlWriter for the file directly:

var settings = new XmlWriterSettings
{
    Indent = true
};

using (var writer = XmlWriter.Create(strXmlName, settings))
{
    xDoc.WriteTo(writer);
}

The encoding here will default to UTF-8.

As an aside, I'd suggest you check out the much newer XDocument and friends, it's a much more friendly API than XmlDocument.

Upvotes: 2

Related Questions