C# XmlTextWriter Example

Extensible markup language (XML)

You want to write XML data to a string in the memory of your C# program. With XmlTextWriter, you can write to an underlying buffer such as a StringWriter and then render the XML to a string.

Example

Note

First, this program includes the System.Xml namespace and also the System.IO namespace. These are for the XmlTextWriter and also the StringWriter. To get started, the program creates an array of four Tuple instances. These represent employee data in a very small company.

StringWriter Class Tuple Tips

This C# example uses the XmlTextWriter type from System.Xml.

Program that uses XmlTextWriter [C#]

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

class Program
{
    static void Main()
    {
	// Create an array of four Tuple instances containing employee data.
	var array = new Tuple<int, string, string, int>[4];
	array[0] = new Tuple<int, string, string, int>(1, "David", "Smith", 10000);
	array[1] = new Tuple<int, string, string, int>(3, "Mark", "Drinkwater", 30000);
	array[2] = new Tuple<int, string, string, int>(4, "Norah", "Miller", 20000);
	array[3] = new Tuple<int, string, string, int>(12, "Cecil", "Walker", 120000);

	// Use StringWriter as backing for XmlTextWriter.
	using (StringWriter str = new StringWriter())
	using (XmlTextWriter xml = new XmlTextWriter(str))
	{
	    // Root.
	    xml.WriteStartDocument();
	    xml.WriteStartElement("List");
	    xml.WriteWhitespace("\n");

	    // Loop over Tuples.
	    foreach (var element in array)
	    {
		// Write Employee data.
		xml.WriteStartElement("Employee");
		{
		    xml.WriteElementString("ID", element.Item1.ToString());
		    xml.WriteElementString("First", element.Item2);
		    xml.WriteWhitespace("\n  ");
		    xml.WriteElementString("Last", element.Item3);
		    xml.WriteElementString("Salary", element.Item4.ToString());
		}
		xml.WriteEndElement();
		xml.WriteWhitespace("\n");
	    }

	    // End.
	    xml.WriteEndElement();
	    xml.WriteEndDocument();

	    // Result is a string.
	    string result = str.ToString();
	    Console.WriteLine("Length: {0}", result.Length);
	    Console.WriteLine("Result: {0}", result);
	}
    }
}

Output

Length: 441
Result: <?xml version="1.0" encoding="utf-16"?><List>
<Employee><ID>1</ID><First>David</First>
  <Last>Smith</Last><Salary>10000</Salary></Employee>
<Employee><ID>3</ID><First>Mark</First>
  <Last>Drinkwater</Last><Salary>30000</Salary></Employee>
<Employee><ID>4</ID><First>Norah</First>
  <Last>Miller</Last><Salary>20000</Salary></Employee>
<Employee><ID>12</ID><First>Cecil</First>
  <Last>Walker</Last><Salary>120000</Salary></Employee>
</List>

StringWriter and XmlTextWriter. The StringWriter is used as a backing store for the XmlTextWriter. This means that as you use the XmlTextWriter, it internally writes to the StringWriter instance you passed to it.

WriteStartDocument and WriteStartElement. Next we see the WriteStartDocument and WriteStateElement methods. These simply begin the XML document and then begin an element. When you pass a string to WriteStartElement, the XmlTextWriter then will know what the element tag is you are writing.

Foreach loop construct

Foreach loop. Next, we see a foreach loop that enumerates the array of Tuple instances. In each iteration of the loop, we write an Employee element. We use WriteElementString to write simple tags with the data enclosed for the Tuple data items.

Foreach Loop Examples

WriteWhitespace. You will notice there are some calls to WriteWhitespace in the code. These are present to make the output look a bit nicer. They do not affect the correctness of the XML.

WriteEndElement and WriteEndDocument. Finally, we see a matching pair of WriteEnd methods. These match the WriteStart methods called earlier (WriteStartDocument and WriteEndElement). It is really important you match all Start methods with End methods.

Summary

The C# programming language

This tutorial exposes several important principles of using XmlTextWriter. After constructing XmlTextWriter with a backing stream, you must use WriteStartDocument. Then, WriteStartElement and WriteElementString can construct elements. All Start methods must be matched by End methods such as WriteEndDocument. Finally, we returned the XML result in a string instance.

XML Tutorials
.NET