In a previous article, we showed you how to parse an XML document tree with ASP.NET's XmlDocument() object, and then use that knowledge to add an RSS feed to your Web site. But reading XML is only a small part of the ASP.NET XML framework's capability.
A close cousin of the XmlDocument() object is ASP.NET's XmlTextWriter() object, which allows developers to dynamically create XML files, using a set of built-in properties and methods. If all your work involves parsing XML data supplied by an external agency, it's quite likely you'll never need this object. But if the shoe's on the other foot and you happen to be the one responsible for creating the data, the XmlTextWriter() object will rapidly become your best friend.
In this article, we'll show you how to use ASP.NET code to dynamically build an XML file, and then apply that knowledge to create an RSS-compliant news file that you can publish on your site (or even decipher with the RSS reader you created last time).
Let's begin with a simple, illustrative example—dynamically generating an XML list of movies from an ASP.NET array. Begin by copying the code in Listing A into a text file, and executing it through your browser.
View the source code of the output of the script in Listing A in your browser, and you'll see the following well-formed XML file:
<?xml version="1.0" encoding="utf-8"?><!—My Movie
Collection—><movies><movie><title>Harry Potter and the Chamber of
t></movie><movie><title>Harry Potter and the Prisoner of Azkaban
When it comes to XML, you have to import the System.Xml assembly, which makes it possible to create an instance of the XmlTextWriter() object, by passing the object constructor two parameters: the location and name of the output file, and the encoding to be used. Most often, you will leave the encoding at the default value (UTF-8), but if you have special requirements, feel free to experiment with this, and also with the System.Text.Encoding class as described in detail in the MSDN Library.
A brief look at the script in Listing A reveals that this is actually pretty straightforward, because the XmlTextWriter() object exposes a bunch of methods corresponding to the various structures supported by the XML format. So, you begin with the WriteStartDocument() method, which generates the initial <?xml ... ?> declaration, and then proceeds rapidly to the WriteStartElement() method, which inserts the root <movies> element. For elements that contain character data, the WriteElementString() method accepts both the element name and its value, and creates both opening and closing elements with the value in between them.
Once all the elements and character data are inserted, a WriteEndElement() method takes care of closing elements previously opened by calls to WriteStartElement(). And inserting a comment in the XML file is as easy as invoking the WriteComment() method and passing the string as a parameter.
To round things up, the Flush() method takes the XML structure from memory and writes it to the named file, and the Close() method clears up vital processor memory for other activities.
Keep in mind
Tip: Remember that the output folder for the final XML file must have the appropriate write permissions for the ASP.NET user. Novices often miss out on this, leading to some head-scratching when the script doesn't work as advertised.
So that was pretty simple. Now, let's put it to practical use by using the XmlTextWriter() to create an RSS file containing the latest news from a Web site or blog. The RSS specification lays down the ground rules for creating the required XML file; read it so that you know what the final output format is supposed to look like.
We'll assume that the data source used for the RSS feed is a database table called "articles", as shown in Figure A.
|Articles database table|
After comparing the structure of the "articles" table above with the RSS specification, it is clear that the "title" of the article maps to the RSS <title> element, the "author" maps to the <author> element, the "abstract" to the <description> element, and the "datepublished" field to the <pubDate> element.
The task at hand is thus clear: retrieve the records from the database table using a SqlDataReader(), and then map them to appropriate elements of the RSS-compliant XML file with an XmlTextWriter().
The first thing that should catch your eye is the neatly-formatted output, which is very different from the XML file created in the previous example. The secret behind this amazing transformation will be revealed shortly, after we explain how the script works.
Since this script involves communicating with a database as well as with an XML file, it is necessary to import three assemblies right off the bat: System.Xml, System.Data, and System.Data.SqlClient. Next, a database connection string is created, and the WriteStartDocument() method is used to initialize the XML document. Note the use of the new WriteAttributeString() method, which attaches a "version" attribute to the root <rss> element.
After invoking the WriteStartElement() method to insert the <channel> element, the WriteElementString() method is used to insert RSS elements that describe the nature of the feed. Next, a standard SELECT query is performed on the "articles" table and an <item> element is appended to the XML document tree, one for each article (typically, this query would contain additional constraints to ensure that only the latest articles are retrieved from the database).
Within each <item>, supplementary <title>, <link>, <description>, <author>, <category>, and <pubDate> elements are inserted, with their values retrieved from the appropriate fields of the "articles" table, as described earlier.
Once all the records are processed, the output is flushed to a file, to create the result in Listing C.
The neatly-indented output comes from the "Formatting" property of the XmlTextWriter() object. This property is an enumeration that accepts one of two values: "Indented" and "None". If you choose the former, you can also specify a custom integer value that indicates how many spaces each indent equals.
That's about it for the XmlTextWriter() object. As these two examples demonstrate, this object is pretty intuitive to use, and comes in handy when you're creating XML from an external data source, be it a CSV file, an MS-SQL database or a data stream. Play with it a little, and see how far your imagination takes you.