The greatest fundamental purpose of XML is that it allows the sharing of information between disparate systems. My last column discussed one side of this sharing – how to read and search through an XML document. Now let’s take a look at the tools available in C# .Net for generating your own XML.
Code Block 1 should be almost self-explanatory to an experienced programmer. The concept is simple: Write an opening element tag, write your data, and write the closing element tag. The WriteEndElement method works off the same idea as the closing curly brace used in most modern programming languages (C# included) – it closes the most recently opened nesting.
The XmlTextWriter constructor used on Line 5 sends output to the console, but there is an alternate constructor available to write the XML to a file, using the specified character encoding.
Line 6 simply formats the XML for readability, indenting all nested blocks. The output looks like this:
Obviously, an XML file on its own doesn’t display information in the most attractive format. In fact, this is another fundamental purpose of XML – the separation of data and presentation. XSL (Extensible Stylesheet Language) is used to apply formatting to an XML document. A stylesheet, or template, is defined in a separate file with an .xsl extension.
Code Block 2 demonstrates a simple transformation utility that will merge an XML document with an XSL file to create an HTML file containing formatted information.
Line 7 loads the stylesheet into the XslTransform object. The Transform method, called on Line 8, takes two filenames as arguments – the first being the source XML document, the second being the desired output file.
The fact that such a powerful application can be created using only 10 lines of code is a credit to the .Net platform. Microsoft has taken great pains to give developers a massive arsenal of tools, especially in the area of XML handling.
My initial foray into .Net development has given me a very good impression of the technology and the direction Microsoft is taking. Of course, being a Java programmer at heart, I still haven’t forgiven the company for its childish rivalry with Sun Microsystems. I’d like to see the two companies coexist more peacefully; even co-operatively (I can dream, can’t I?). If there’s one thing that will slow acceptance of .Net, it’s the practical necessity of choosing it over a very formidable competitor.
My next column will shed the C# focus to examine formatting with XSL.
Cooney works as a programmer/analyst for a major Canadian book publisher. He can be reached at [email protected].