When you create a string of Xml using the XmlWriter and StringWriter, the string will have the encoding set at "utf-16" in the first line
i.e.
<?xml version="1.0" encoding="utf-16"?>
This is because StringWriter (http://msdn2.microsoft.com/en-us/library/system.io.stringwriter.aspx) only produces "utf-16" output, as strings are always "utf-16" in .Net
Refer:
Encodings in the .NET Framework
http://www.microsoft.com/globaldev/getWR/steps/wrg_codepage.mspx
"utf-16" Vs "utf-8"
http://www.thescripts.com/forum/thread177860.html
There is no way to get this as in "utf-8" using the StringWriter
i.e. the following is not possible
<?xml version="1.0" encoding="utf-8"?>
Because of this restriction, while creating the XmlWriter, we need to use the XmlWriterSettings and set the encoding to Encoding.Unicode. Note "Unicode" in Encoding.Unicode means "utf-16" as per MS terminology. ( http://msdn2.microsoft.com/en-us/library/system.text.encoding.aspx )
Code sample:
public static string ConstructXml()
{
StringWriter stringWriter = new StringWriter();
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = false; //already the default
settings.ConformanceLevel = ConformanceLevel.Document; //already the default
settings.NewLineOnAttributes = true;
settings.Indent = true;
settings.IndentChars = "\t";
settings.Encoding = Encoding.Unicode; //strings in .NET are by default encoded as "utf-16", "Unicode" in MS terminology is "utf-16"
XmlWriter writer = XmlWriter.Create(stringWriter, settings);
//use the different write methods
//writer.WriteAttributes(...)
//writer.WriteAttributeString(...)
//writer.WriteElementString(...)
//finally construct a string out of it
string xmlString;
xmlString = stringWriter.ToString();
return xmlString;
}