Sunday, November 16, 2008

Creating / Writing XML Documents with the XmlTextWriter Class

The .NET Framework provides a class designed specifically to create XML documents, theSystem.Xml.XmlTextWriter class. By using this class to create XML documents you don't need to worry about illegal XML characters in the text portion of the XML document, and the end code is much cleaner. In this article we'll look at using the XmlTextWriter class to create XML documents on the fly.

The Basics of the XmlTextWriter Class
The 
XmlTextWriter class contains a number of methods that are useful for starting and completing an XML document and for adding elements and attributes to the XML document. The most important methods are:

  • WriteStartDocument() - you should call this method to start creating an XML document. This will create the first line in the XML document, specifying that the file is an XML document and its encoding.
  • WriteStartElement(string) - this method creates a new element in the XML document with the name specified by the string input parameter. (You can also specify a namespace as a second, optional string parameter.)
  • WriteElementString(nametext_value) - If you want to create an XML element with nothing but text content (i.e., no nested elements), you can use this method.
  • WriteAttributeString(namevalue) - this method writes an attribute name and value to the current element.
  • WriteEndElement() - this method closes off the element created in theWriteStartElement(string) method call.
  • WriteEndDocument() - this method completes the writing of the XML document.
  • Close() - this method closes the underlying stream, writing the contents of the XML document to the specified file location.

To get started using the XmlTextWriter class you need to specify the file and encoding in the class's constructor. The encoding needs to be of the type System.Text.Encoding; some example encoding values are: System.Text.Encoding.ASCIISystem.Text.Encoding.Unicode, andSystem.Text.Encoding.UTF8. Alternatively, you can specify in the constructor that the output of the XmlTextWriter class should be squirted out to a specified Stream.

Creating a Simple XML Document with XmlTextWriter
To demonstrate using the 
XmlTextWriter class let's create a simple XML document, saving it to a specified file location. This XML document will contain information about the current user visiting the page, and will have this structure:



URL referrer info

User agent referrer info

languages info


date/time the page was visited">

visitor's IP address

raw URL requested


(This XML file structure was chosen so that it would illustrate using all of the XmlTextWritermethods discussed in the previous section.)

The code needed to create this XML document through an ASP.NET Web page is shown below:

<%@ Import Namespace="System.Xml" %>

<%@ Import Namespace="System.Text" %>