A Simple Way to Write XML in .NET (XmlTextWriter)

Environment: .NET (C#)

XML is a hot topic. A primary reason for it being of interest is the fact that it is simple to understand and simple to use. Any programmer should be able to easily look at an XML file and understand its contents.

.NET contains a number of classes that support XML. Many of these classes make working with XML as easy as understanding XML. I'm going to show you an example of one such class here. This is the XmlTextWriter class.

The XmlTextWriter class allows you to write XML to a file. This class contains a number of methods and properties that will do a lot of the work for you. To use this class, you create a new XmlTextWriter object. You then add the pieces of XML to the object. There are methods for adding each type of element within the XML file. Following are several of these methods:

METHODDESCRIPTION
WriteStartDocumentWrites the XML declaration with the version "1.0".
WriteEndDocumentCloses any open elements or attributes.
CloseCloses the stream.
WriteDocTypeWrites the DOCTYPE declaration with the specified name and optional attributes.
WriteStartElementWrites the specified start tag.
WriteEndElementCloses one element.
WriteFullEndElementCloses one element.
WriteElementStringWrites an element containing a string value.
WriteStartAttributeWrites the start of an attribute.
WriteEndAttributeCloses the previous WriteStartAttribute call.
WriteRawWrites raw markup directly from a string.
WriteStringWrites a string.
WriteAttributesWrites an attribute with the specified value.
WriteCDataWrites out a <![CDATA[...]]> block containing the specified text.
WriteCommentWrites out a comment <!--...--> containing the specified text.
WriteWhitespaceWrites white space.
WriteProcessingInstructionWrites out a processing Instruction with a space between the name and text as follows: <?name text?>.

If you are familiar with XML, then the above methods should make sense. You will create a document, add elements, and then close the document. Within elements you can add sub-elements, attributes, and more. The following listing creates a new XML file called titles.

using System;
using System.IO;
using System.Xml;

public class Sample
{ 
  public static void Main()
  {
     XmlTextWriter writer = new XmlTextWriter("titles.xml", null);

     //Write the root element
     writer.WriteStartElement("items");

     //Write sub-elements
     writer.WriteElementString("title", "Unreal Tournament 2003");
     writer.WriteElementString("title", "C&C: Renegade");
     writer.WriteElementString("title", "Dr. Seuss's ABC");

     // end the root element
     writer.WriteEndElement();
             
     //Write the XML to file and close the writer
     writer.Close();  
  }
}

If you compile and execute this listing, you will create an XML file called titles.xml. This XML file will contain the following:

<items><title>Unreal Tournament 2003</title><title>
C&amp;C: Renegade</title><title>Dr. Seuss's ABC
</title></items>

The listing created an XmlTextWriter object called writer. When it created this object, it associated it to a file called titles.xml. The program then started a root element called items. The call to WriteStartElement created the opening tag for items. This was then followed by three calls to WriteElementString. As you can see, this method creates an element tag using the first parameter (title in this case). The value of the element is the second parameter. Once you are done adding the elements, you need to close the root element. Calling WriteEndElement will close the element that was most recently opened. In this case, that is the root element. With all the data written and the root element closed, you are done sending information to your XmlTextWriter. This means you can close it by calling the Close method.

This listing is relatively simple. The following listing includes a lot more functionality by using more of the XmlTextWriter methods.

using System;
using System.IO;
using System.Xml;

public class Sample
{
  public static void Main()
  {
     XmlTextWriter writer = new XmlTextWriter("myMedia.xml", null);

     //Use automatic indentation for readability.
     writer.Formatting = Formatting.Indented;

     //Write the root element
     writer.WriteStartElement("items");

     //Start an element
     writer.WriteStartElement("item");

     //Add an attribute to the previously created element 
     writer.WriteAttributeString("rating", "R");

     //add sub-elements
     writer.WriteElementString("title", "The Matrix");
     writer.WriteElementString("format", "DVD");

     //End the item element
     writer.WriteEndElement();  // end item

     //Write some white space between nodes
     writer.WriteWhitespace("\n");

     //Write a second element using raw string data
     writer.WriteRaw("<item>" + 
                     "<title>BloodWake</title>" +
                     "<format>XBox</format>" + 
                     "</item>");

     //Write a third element with formatting in the string
     writer.WriteRaw("\n  <item>\n" +
                     "    <title>Unreal Tournament 2003</title>\n" +
                     "    <format>CD</format>\n" + 
                     "  </item>\n");

     // end the root element
     writer.WriteFullEndElement();

     //Write the XML to file and close the writer
     writer.Close();
  }
}

The output for this listing is stored in a file called myMedia.xml:

<items>
  <item rating="R">
    <title>The Matrix</title>
    <format>DVD</format>
  </item>
<item><title>BloodWake</title><format>XBox</format></item>
  <item>
    <title>Unreal Tournament 2003</title>
    <format>CD</format>
  </item>
</items>

The comments within the listing tell you what is happening. One thing to remember is that methods that start something, need to be followed at some point by methods that end what was started. For example, if you call StartElement, you will need to call EndElement. You can start a sub-element within another element. Whenever you call an EndElement method, it will always associate with the last StartElement method that was called. (This works like a stack, not like a queue).

Working with the XmlTextWriter is easy. I suggest you play around with the code and the various methods. You'll quickly find that this code is easy to integrate into your applications. You should also remember that the XmlTextWriter is only one of many XML classes available in .NET. Like the XmlTextWriter, many of the other classes are also easy to use.



About the Author

Bradley Jones

Bradley Jones, in addition to managing CodeGuru, Brad! oversees the Developer.com Newtwork of sites including Codeguru, Developer.com, DevX, VBForums, and over a dozen more with a focus on software development and database technologies. His experience includes development in C, C++, VB, some Java, C#, ASP, COBOL, and more as well as having been a developer, consultant, analyst, lead, and much more. His recent books include Teach Yourself the C# Language in 21 Days, Web 2.0 Heroes, and Windows Live Essentials and Services.
Google+ Profile | Linked-In Profile | Facebook Page