Simple XML Output Using The XmlTextWriter Class

Posted: (EET/GMT+2)

 

Simple XML Output Using The XmlTextWriter Class

Dec 30, 2002

Microsoft Visual Studio .NET

Nowadays many applications you create need XML output. Having an easy-to-use class library at your disposal is a great advantage. When you are using .NET, you do have such a class library. From the System.Xml namespace you can find the XmlTextWriter class which does the job for you.

When you need to output XML to a stream (remember, in .NET almost anything can be accessed as a stream) or even to the console, you can use the XmlTextWriter class. This class contains easy methods like WriteStartElement and WriteAttributeString that allow you to generate XML in your code.

For instance, assume you would need to generate the following piece of XML to store customer information:

<customers>
  <customer id="1">
		<name>Customer name #1</name>
		<address>Customer address #1</address>
	</customer>
	<customer id="2">
		<name>Customer name #2</name>
		<address>Customer address #2</address>
	</customer>
	<customer id="3">
		<name>Customer name #3</name>
		<address>Customer address #3</address>
	</customer>
</customers>

Of course, in reality the customer data would be more intelligent, but you get the point. Next, let us show you how to generate this XML snippet in code.

How to do it in C#

If you C# as your .NET programming language (highly recommended, at least at this point in time), you can use the following code directly. Had you chosen to use some other language, you would need to adjust the code, but then again, manipulating the XmlTextWriter class would stay the same.

The code of a very simple console application that outputs the preceding XML to the System.Console.Out:

using System;
using System.Xml;

namespace SimpleXMLOutput
{
	class XMLOutputDemo
	{
		[STAThread]
		static void Main(string[] args)
		{
			System.Xml.XmlTextWriter xmlWriter =
				new XmlTextWriter(System.Console.Out);
			
			// use nice formatting for the XML
			xmlWriter.Formatting = Formatting.Indented;

			// write out the customer elements
			xmlWriter.WriteStartElement("customers");
			for (int i = 1; i <= 3; i++) 
			{
				// write out the individual customers here
				xmlWriter.WriteStartElement("customer");
				xmlWriter.WriteAttributeString("id",i.ToString());
					xmlWriter.WriteStartElement("name");
						xmlWriter.WriteString("Customer name #"+i);
					xmlWriter.WriteEndElement();
					xmlWriter.WriteStartElement("address");
						xmlWriter.WriteString("Customer address #"+i);
					xmlWriter.WriteEndElement();
				xmlWriter.WriteEndElement();
			}

			// final closing tag
			xmlWriter.WriteEndElement();
			
			// close everything
			xmlWriter.Close();
		}
	}
}

Again, you would replace the for loop with something more meaningful, but the important thing is to note how the XmlTextWriter class is used. Also note how we’ve indented the xmlWriter class so that the program logic is easier to follow.

How it works

When constructing the XmlTextWriter class, you need to provide it with an output stream or a System.IO.TextWriter object. For example, common streams would be System.IO.FileStream or even the System.Net.Sockets.NetworkStream class. In the example code, the System.Console.Out TextWriter object is used for simplicity.

Next, the code sets the Formatting property of the xmlWriter object. Specifying Formatting.Indented results in a nicely indented XML string, as in the following picture:

The sample application

When you want to start a new XML element, call the WriteStartElement method of the XmlTextWriter class. An element must be closed by calling the WriteEndElement method, but it is important to understand when to do this. For example, if you call WriteStartElement twice, the second element will be a child element of the element created with the first call.

XmlTextWriter also contains other interesting methods such as WriteAttributeString. This method allows you to add an attribute to a newly started element. So, the call to WriteAttributeString should follow a call to WriteStartElement, for instance.

Finally, to write the actual element value, you could use the WriteString method. There are also other methods like WriteBase64, WriteCData and WriteRaw, among other such goodies.

As you can see, even a simple-looking class like XmlTextWriter can provide wealth of functionality. We just wish other programming environments and languages would be as easy to use!

Download the example code

Download simplexmloutputusingthexmltextwriterclass.zip (7 KB) which contains the sample application presented in this article. Please note that the sample application will require the Microsoft .NET SDK to be installed to compile.

* * *

Do you need consulting help in getting your .NET project started? Contact us today!