Chris's coding blog

Using XmlTextWriter to produce a XML string

February 16, 2010

This is a small snippet showing an example of using a XmlTextWriter to produce Xml that validates.

One point to note is that because .NET strings are held internally as double-byte UTF16, using a StringWriter will always output to UTF16. If you try to force it down, the byte-order of the file will be wrong. Make sure if you’re using File.WriteAllText, you use the overloaded version and specify Encoding.Unicode or it will write your string as UTF-8 with not Byte Order Mark. This confuses Visual Studio so that it doesn’t open the files correctly.

Using UTF8 can cause some problems when you store XML inside databases (or specifically SQL Server). Also some XML pads don’t like UTF16 so you may need to convert the string to UTF8 for editing if you’re only using Western characters, shown in the second method.

public static string ToXml()
{
StringBuilder builder = new StringBuilder();
using (StringWriter stringWriter = new StringWriter(builder))
{
using (XmlTextWriter writer = new XmlTextWriter(stringWriter))
{
// This produces UTF16 XML
writer.Indentation = 4;
writer.IndentChar = '\t';
writer.Formatting = Formatting.Indented;
writer.WriteStartDocument();
writer.WriteStartElement("Root");
writer.WriteAttributeString("myattrib", "123");
writer.WriteEndElement();
writer.WriteEndDocument();
}
}
return builder.ToString();
}
public static string ToUTF8Xml()
{
string result;
MemoryStream stream = new MemoryStream(); // The writer closes this for us
using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8))
{
writer.Indentation = 4;
writer.IndentChar = '\t';
writer.Formatting = Formatting.Indented;
writer.WriteStartDocument();
writer.WriteStartElement("Root");
writer.WriteAttributeString("myattrib", "123");
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
// Make sure you flush or you only get half the text
writer.Flush();
// Use a StreamReader to get the byte order correct
StreamReader reader = new StreamReader(stream, Encoding.UTF8, true);
stream.Seek(0, SeekOrigin.Begin);
result = reader.ReadToEnd();
// #2 - doesn't write the byte order reliably
//result = Encoding.UTF8.GetString(stream.GetBuffer(), 0, (int)stream.Length);
}
// Make sure you use File.WriteAllText("myfile", xml, Encoding.UTF8);
// or equivalent to write your file back.
return result;
}
view raw gistfile1.cs hosted with ❤ by GitHub

csharpxml

I'm Chris Small, a software engineer working in London. This is my tech blog. Find out more about me via GithubStackoverflowResume