With your code sample, you are missing the part to tells the XmlTextWriter what encoding to use. If you use any class that is derived from a TextWriter (like StringWriter), then you can't specify the encoding. The reason for this is that the base string in a StringWriter is UTF-16, so you have no options for using a different Encoding. If however, you use a MemoryStream, or something derived directly from Stream, then you can specify a different Encoding. Anyway, here is a code snippet that describes this:
MemoryStream ms = new MemoryStream();
//Set the encoding to UTF8:
XmlTextWriter writer = new XmlTextWriter(ms, Encoding.UTF8);
//Just makes the xml easier to read:
writer.Formatting = Formatting.Indented;
//Write out our xml document:
writer.WriteStartDocument();
writer.WriteStartElement("Stock");
writer.WriteAttributeString("Symbol", "123");
writer.WriteElementString("Price", "456");
writer.WriteElementString("Change", "abc");
writer.WriteElementString("Volume", "edd");
writer.WriteEndElement();
//Reset our stream's read pointer, so we can read back from our memory stream:
writer.Flush();
ms.Seek(0, SeekOrigin.Begin);
//Read our memory stream, and output to console:
StreamReader sr = new StreamReader(ms);
string content = sr.ReadToEnd();
Console.WriteLine(content);
return;
It is important to note that you could have used a similar technique in your original code when you used the XmlDocument. The reason why you were getting the UTF-16 encoding is because your underlying writer class was a string. StringWriter writes directly to a string (or possibly a StringBuilder). And because strings in .NET are all UTF-16, that is the encoding you got. When you write directly to a stream (FileStream, MemoryStream, etc), then you are not writing to a string, but conceptually you are writing to just an array of bytes. Because of that you can specify a different encoding. Anyway, I hope this helps you out.