Wednesday, August 29, 2007

Creating / Writing XML Documents with the XmlTextWriter Class

The .NET Framework provides a class designed specifically to create XML documents, the System.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(name, text_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(name, value) - this method writes an attribute name and value to the current element.
  • WriteEndElement() - this method closes off the element created in the WriteStartElement(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.ASCII, System.Text.Encoding.Unicode, and System.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:

<userInfo>

<browserInfo>

<urlReferrer>URL referrer info</urlReferrer>

<userAgent>User agent referrer info</userAgent>

<userLanguages>languages info</userLanguages>

</browserInfo>

<visitInfo timeVisited="date/time the page was visited">

<ip>visitor's IP address</ip>

<rawUrl>raw URL requested</rawUrl>

</visitInfo>

</userInfo>

(This XML file structure was chosen so that it would illustrate using all of the XmlTextWriter methods 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" %>

<script language="C#" runat="server">

void Page_Load(object sender, EventArgs e)

{

// Create a new XmlTextWriter instance

XmlTextWriter writer = new

XmlTextWriter(Server.MapPath("userInfo.xml"), Encoding.UTF8);


// start writing!

writer.WriteStartDocument();

writer.WriteStartElement("userInfo");


// Creating the <browserInfo> element

writer.WriteStartElement("browserInfo");


if (Request.UrlReferrer == null)

writer.WriteElementString("urlReferrer", "none");

else

writer.WriteElementString("urlReferrer",

Request.UrlReferrer.PathAndQuery);


writer.WriteElementString("userAgent", Request.UserAgent);

writer.WriteElementString("userLanguages",

String.Join(", ", Request.UserLanguages));

writer.WriteEndElement();


// Creating the <visitInfo> element

writer.WriteStartElement("visitInfo");

writer.WriteAttributeString("timeVisited", DateTime.Now.ToString());

writer.WriteElementString("ip", Request.UserHostAddress);

writer.WriteElementString("rawUrl", Request.RawUrl);

writer.WriteEndElement();


writer.WriteEndElement();

writer.WriteEndDocument();

writer.Close();

}

First, notice that the System.Xml and System.Text namespaces have been imported. The Page_Load event handler begins by creating a new XmlTextWriter instance, indicating that its content should be saved to the file userInfo.xml and that its encoding should be UTF8 (a translation of 16-bit unicode encoding into 8-bits). Note that for each element with nested elements a WriteStartElement(elementName) method is called, along with a matching WriteEndElement() after the inner content has been renderred. Furthermore, the WriteElementString(elementName, textValue) is used for those elements with just text content.

Emitting XML Content to the Browser Window Directly
The previous example demonstrates how to use the
XmlTextWriter class to create an XML document and persist it to a file. While this may be precisely what you are after, oftentimes when creating an XML document in an ASP.NET Web page we want to emit the XML content's to the client requesting the Web page. While this could be done in the previous example by opening the userInfo.xml file after creating it and then Response.Write()ing its contents out, this approach is a bit of a hack.

A better approach is to have the results of the XmlTextWriter emitted directly to the output stream. This can be accomplished quite easily, by changing one line of code in the previous code sample. In the XmlTextWriter constructor, rather than specifying a file path, we can specify a Stream. Specifically, we want to specify Response.OutputStream. When doing this you will need to make another small change to the ASP.NET Web page. In the <@ Page ... > directive you need to indicate the page's MIME type as text/xml. If you don't do this, some browsers may think the data being sent is for a standard HTML Web page, and will attempt to format the XML document just as they would an HTML page (which will hide the XML elements and remove all whitespace).

The following code shows an abbreviated version of the previous code sample, with the changes in bold.

<@ Page ContentType="text/xml" %>

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

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

<script language="C#" runat="server">

void Page_Load(object sender, EventArgs e)

{

// Create a new XmlTextWriter instance

XmlTextWriter writer = new

XmlTextWriter(Response.OutputStream, Encoding.UTF8);


// start writing!

...

}

Notice that by viewing the live demo you are shown an XML document (even though you are visiting an ASP.NET Web page). This is the same XML document that, in the previous code sample, was saved to userInfo.xml.

No comments:

 
Dotster Domain Registration Special Offer