You may have noticed the first line of XML output generated by XmlWriter or XmlTextWriter shows that the encoding defaults to UTF-16:
<?xml version="1.0" encoding="utf-16"?>
This happens even if you explicitly set the Encoding property in the XmlWriterSettings to something different, such as UTF-8:
StringBuilder sb = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings (); settings.Encoding = System.Text.Encoding.UTF8; XmlWriter writer = XmlWriter.Create (sb, settings);
The problem occurs because the StringWriter defaults to UTF-16. (It’s not clear from the example above, but the XmlWriter class uses a StringWriter to output the XML to the specified StringBuilder.)