.Net gives XML tools out of the box
Published: 05 Nov 2002 14:18 GMT
Much has been said about .Net's use of XML, and unfortunately, a lot if it is hyperbole. Still, two things are undeniable: .Net puts an integrated set of XML tools into the programmer's hands, and this is really the first time a Microsoft development platform has had integrated XML support out of the box. This is complete support, with well over 150 classes to be found in the System.XML namespace, a dizzying number.
The "pull model" vs. the DOM and SAX
If you've used XML before, you're probably familiar with the two main flavors of parser that are available, the Document Object Model (DOM) and the Simple API for XML (SAX). These two parser types operate in fundamentally different ways: DOM loads an entire XML document into a hierarchical tree in memory, while SAX runs through a document one element at a time, handing each element back to an application through some kind of communication interface.
The DOM? SAX? What's that?
Both these APIs have their respective problems, as well. The DOM is terribly consumptive of resources, especially with large documents. SAX is not very intuitive to use, requires the programmer to keep track of previously processed elements, and doesn't really provide a way to work only with selected parts of a document.
The .Net XML classes strive to reach a happy medium between these two APIs and incorporate the best features of both into something Microsoft calls the "pull model." Not much of a name, I know. I'd have called it XML streams or XML stack, but I suppose those wouldn't be sexy enough. Anyway, with .Net, you use the pull model classes to parse and create XML documents using a simple stream-like interface. Two abstract classes, System.XML.XMLWriter and System.XML.XMLReader provide the basis for .Net's pull model XML support.
Writing XML with XMLWriter WriteAttributeString Writes an attribute with the specified string value WriteCData Writes out a CDATA section containing the specified text WriteComment Writes a comment: WriteElementString Writes an element containing a string value WriteProcessingInstruction Writes a processing instruction: ... ?> WriteRaw Writes raw XML to the stream WriteStartDocument Writes the XML declaration that should appear at the start of every document WriteString Writes a string value WriteWhitespace Writes whitespace
The XMLWriter class is essentially an XML-aware wrapper for an output stream that makes creating an XML document a breeze. The class includes methods for writing all types of XML content, as you can see in Figure A.Figure A
XMLWriter's XML content creation methods
The XMLTextWriter class is a concrete child class of XMLWriter that you can use in your applications as is. Simply pass an instance of an output stream object to the constructor and begin writing XML. You could also extend the base XMLWriter class yourself and create a custom writer if you so desire.








