Friday, April 25, 2008

XmlWriter

To create this in code:
<?xml version="1.0" encoding="utf-16"?><Person><FirstName>Mark</FirstName><LastName>Moeykens</LastName></Person>
You can code it this way:
StringBuilder sb = new StringBuilder();
using(XmlWriter writer = XmlTextWriter.Create(sb))
{
    writer.WriteStartElement("Person");
    writer.WriteElementString("FirstName", "Mark");
    writer.WriteElementString("LastName", "Moeykens");
    writer.WriteEndDocument();
}
Console.Write(sb.ToString());
The
<?xml version="1.0" encoding="utf-16"?>
bugs me though. I never seem to have a use for it in my code so let's get rid of it.

To do that, we have to introduce some settings for our writer using the XmlWriterSettings class then pass it into the XmlTextWriter.Create method.
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;

StringBuilder sb = new StringBuilder();
using(XmlWriter writer = XmlTextWriter.Create(sb, settings))
{
    writer.WriteStartElement("Person");
    writer.WriteElementString("FirstName", "Mark");
    writer.WriteElementString("LastName", "Moeykens");
    writer.WriteEndDocument();
}
Console.Write(sb.ToString());
Output:
<Person><FirstName>Mark</FirstName><LastName>Moeykens</LastName></Person>
That's better. Now let's add another setting to get the elements on their own line and indented:
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.Indent = true;

StringBuilder sb = new StringBuilder();
using(XmlWriter writer = XmlTextWriter.Create(sb, settings))
{
    writer.WriteStartElement("Person");
    writer.WriteElementString("FirstName", "Mark");
    writer.WriteElementString("LastName", "Moeykens");
    writer.WriteEndDocument();
}
Console.Write(sb.ToString());
Output:
<Person>
  <FirstName>Mark</FirstName>
  <LastName>Moeykens</LastName>
</Person>
There we go, this looks much better!

More Info: MSDN: Creating XML Writers