Streamed Access
Perhaps the biggest innovation in the System.Xml namespace, and the way in which you'll typically interact with XML documents, is through the use of a stream-based API analogous to the stream reading and writing performed on files discussed in Chapter 11. At the core of this API are the XmlReader and XmlWriter classes, which provide read-only, forward-only cursor access to XML documents and an interface for writing out XML documents, respectively. Since these class implement a stream-based approach, they do not require that the XML document be parsed into a tree structure and cached in memory as happens when working with the document through the DOM.
Using an XML Reader
When the DOM was first published and vendors such as Microsoft began writing parsers like MSXML to read those documents, it became immediately apparent that the programming model was not ideal for all applications. This was particularly the case when the XML document was large, since by definition the DOM represents the entire document in an in-memory tree structure. Not only did performance suffer using the DOM since you had to wait for the document to be parsed and loaded, but the application processing the document tended to eat up significant amounts of memory. As a result, Microsoft included the SAX APIs in MSXML 3.0 to provide an event-driven programming model for XML documents. While this alleviated the performance and memory constraints of the DOM, it did so at the cost of complexity.
The XmlReader implementation is in many ways a melding of the DOM and SAX and provides a simplified programming model like the DOM but in a stream-based architecture. The programming model is simplified because it is a pull rather than a push model. In other words, developers pull data from the document using a familiar cursor-style looping construct rather than simply being pushed data by responding to events fired from the parser.
The XmlReader class is actually an abstract base class for the XmlTextReader, XmlValidatingReader, and XmlNodeReader classes. The XmlReader is often used as the input or output arguments for other methods in the Services Framework. A typical use of the XmlTextReader is to read XML produced from the FOR XML statement in SQL Server 2000 and then load a DataSet object as shown in the following code:
Imports System.Xml Imports System.Data.SqlClient Imports System.Data Dim cn As New SqlConnection("server=ssosa;database=enrollment;uid=sa") Dim cm As New SqlCommand( _ "SELECT FName, LName, Company FROM Student FOR XML AUTO, XMLDATA", cn) Dim xmlr As XmlReader Dim ds As New DataSet() cn.Open() cm.CommandType = CommandType.Text xmlr = cm.ExecuteXmlReader ds.ReadXml(xmlr, XmlReadMode.Fragment)
Note that the ExecuteXmlReader method of the SqlCommand object returns an XmlReader which is then accepted as an argument to one of the overloaded ReadXml methods of the DataSet object. As discussed in Chapter 7, the second argument to the ReadXml method specifies how the XML is parsed using one of the XmlReadMode constants.
As implied by the names, XmlTextReader simply provides a reader that checks for well-formedness of an XML document and any inline DTDs but does not perform validation using an associated DTD or schema as does XmlValidatingReader. As a result, XmlTextReader is the fastest way to parse an XML document using a file, Stream, or TextReader as input. XmlNodeReader, on the other hand, can parse XmlNode objects from an XML DOM subtree, as will be discussed later. To give you a feel for the readers, the important members or the XmlTextReader class are shown in Table 13.2.
Table 13.2 Important XmlTextReader members.
Member |
Description |
AttributeCount |
Returns the number of attributes on the current node |
BaseURI |
Returns the base URI used to resolve external references to the current node |
Depth |
Returns the depth of the current node within the XML document |
EOF |
Returns True if the XmlReader is positioned at the of the stream |
HasAttributes, HasValue |
Returns True if the current node has attributes or a value |
IsDefault |
Returns True if the attribute of the current node was generated from the default specified in the DTD or schema |
IsEmptyElement |
Returns True if the current node is an empty element |
Item |
Indexed property that returns an attribute from the current node |
LineNumber, LinePosition |
Returns current location information |
LocalName, Name |
Returns the name of the current node without the namespace prefix and the qualified name, respectively |
NodeType |
Returns the XmlNodeType for the current node |
ReadState |
Returns the state of the XmlReader using one of the ReadState constants (Closed, EndOfFile, Error, Initial, Interactive) |
Value |
Returns the value of the current node as a String |
Namespaces, NamespaceURI |
Specifies whether to support namespaces and the namespace of the current node, respectively |
WhitespaceHandling |
Specifies how to parse whitespace encountered in the document |
Close |
Closes the document and changes the ReadState to Closed |
GetAttribute |
Returns the value of the attribute given the index or name. If it does not exist, return an empty string |
GetRemainder |
Returns that part of the document still in the buffer as a TextReader object |
IsStartElement |
Returns True if the current node is a start tag. Also overloaded to accept an element name that first navigates to the next content element using MoveToContent |
MoveToAttribute, MoveToContent, MoveToElement, MoveToFirstAttribute, MoveToNextAttribute |
Methods that navigate to through the document to find the specified data |
Read |
Reads the next node from the stream and makes it the current node |
ReadString, ReadChars, ReadBase64, ReadBinHex |
Reads the value of the text of the current node and returns it in the appropriate data type |
ReadInnerXml, ReadOuterXml |
Reads the current node and its markup as a String and also includes its children, respectively. |
To illustrate the use of XmlTextReader, consider the ExtractStudents method shown in Listing 13.1.
Listing 13.1. Using XmlTextReader. This method uses the XmlTextReader to read the contents of an XML document and extract students names to save in a database.
Imports System.Xml Imports System.IO Imports System.Data.SqlClient Imports System.Data Public Sub ExtractStudents(ByVal pFileName As String) Dim oRead As XmlTextReader Try Dim strFName, strLName, strOrg As String oRead = New XmlTextReader(pFileName) oRead.NameTable.Add("Student") Do While oRead.Read oRead.MoveToContent() If oRead.Name.Equals("Student") And oRead.Depth = 1 Then strFName = oRead.GetAttribute("FName") strLName = oRead.GetAttribute("LName") If oRead.AttributeCount = 3 Then strOrg = oRead.GetAttribute("Company") Else strOrg = "" End If Call SaveStudent(strFName, strLName, strOrg) End If Loop Catch e As XmlException LogMessage(pFileName, e.Message, e.LineNumber, e.LinePosition, oRead.Name) Finally oRead.Close() End Try End Sub
In this example, the ExtractStudents method uses the overloaded constructor of the XmlTextReader class to pass in the name of a file. In addition, the XmlReader exposes an XmlNameTable in the NameTable property that is used to store frequently used strings. By using a name table, the XML parser can reuse the strings in the table when returning element names and can use more efficient object pointer comparisons when doing comparisons. An existing XmlNameTable can also be passed into the constructor so that comparison across readers will also be more efficient.
If the file can be opened a Do Loop is used to iterate through the contents of the document using the Read method, which returns False upon reaching the end of the stream.
One of the interesting aspects of an XmlReader is that the Read method not only returns each tag (begin and end elements, processing instructions, CDATA sections, comments, and document type definitions) but also whitespace. And as you might imagine, it does so in a recursive way such that an entire element including all of its children is processed before moving on to a sibling element. The type of the current node can be checked using the NodeType property.
In order to more efficiently move through the document, you can use the move methods such as MoveToContent, as in this example. MoveToContent skips over any processing instructions, DTDs, comments, and whitespace and moves to the next CDATA section, beginning or ending element, or entity reference.
As mentioned previously, the XmlTextReader will only make sure the document is well-formed and will otherwise throw an XmlException. In this example, both the Read method and the MoveToContent methods may generate the exception since both perform navigation. Note also that once a well-formedness error is encountered, the ReadState of the XmlTextReader is set to Error and no more processing on the document can be performed.
TIP
By logging the LinePosition of the error, as is done here, the method could be easily altered to re-process the document starting with the appropriate line.
NOTE
You can also skip only the whitespace by setting the WhiteSpaceHandling property to the None constant of the WhiteSpaceHandling enumeration.
The element name can then be checked using the Name property before proceeding to read the value of the element using the Value property or one of the read methods shown in Table 13.2.
TIP
In this example, the Depth property is used to ensure that the method only processes top-level Student elements by checking for a depth of 1.
However, you'll notice in this case that the data for the student is actually contained in attributes of the Student element. Attributes are not represented as separate nodes by XmlReader, but rather as a collection associated with the node. As a result, attributes are typically accessed using the Item property or the GetAttribute method. Alternatively, the MoveToAttribute method can be used to position the cursor over the attribute passed to the method, and the Name and Value properties are set to the name of the attribute and its value. The collection can also be navigated in this way using the MoveToFirstAttribute and MoveToNextAttribute methods.
The values are then extracted from the attributes and passed to a method that saves them in the database.
An advanced technique that XmlReader supports, shown in Listing 13.1, is the optional expansion of entity references. Simply put, an entity reference allows an XML document to be compressed by defining an entity once in a document and referencing it multiple times like so:
<!DOCTYPE Classes [ <!ENTITY 2073 "<CourseNum>2073</CourseNum> <CourseDesc>Programming Microsoft SQL Server 2000</CourseDesc>"> ]> <Class> <Course>&2073;</Course> </Class>
When the XmlReader encounters the expression "&2073," the NodeType will be set to EntityReference. By invoking ResolveEntity, the substitution will occur and processing will continue with the CourseNum and CourseDesc elements. Note that XmlTextReader, however, does not support entity referencing, and the CanResolveEntity property can be used to determine whether entities can be resolved.
To perform validation against an XML document, you can associate an XmlValidatingReader object with an XmlTextReader. The XmlValidatingReader exposes a Schemas collection (XmlSchemaCollection) that contains one or more schemas (DTDs, XSD, XDR) represented as XmlSchema objects that can be used to validate the document. Validation errors are then reported through a ValidationEventHandler. The Validate method in Listing 13.2 shows the basics of validating a document using an XDR schema.
Listing 13.2. Validating XML. This method shows how to validate a document against a schema.
Public Sub Validate(ByVal pFileName As String, ByVal pSchema As String, _ ByVal pNamespace As String) Dim oRead As XmlTextReader Dim oValid As XmlValidatingReader Try oRead = New XmlTextReader(pFileName) oValid = New XmlValidatingReader(oRead) AddHandler oValid.ValidationEventHandler, _ New ValidationEventHandler(AddressOf ValidationError) oValid.Schemas.Add(pNamespace, pSchema) oValid.ValidationType = ValidationType.XDR Do While oValid.Read ' Read through the document here Loop Catch e As Exception LogMessage(pFileName, e.Message, e.LineNumber, _ e.LinePosition, oRead.Name) Finally oValid.Close() End Try End Sub Public Sub ValidationError(ByVal o As Object, _ ByVal args As ValidationEventArgs) ' Validation error occurred LogValidationError(args) End Sub
Note that the XmlValidating reader is initialized with the XmlTextReader and the schema added through the Add method of the XmlSchemaCollection. The arguments represent the namespace URI (as it is referred to in the document to be validated) and the URL of the schema to load. The event handler where errors will be reported is created using the AddHandler statement, in this case pointing to the ValidationError method. The schemas must be added to the collection before the Read method is called. The ValidationType property is set to the XDR constant of the ValidationType enumeration.
TIP
By setting the ValidationType property to None, validation will be bypassed. However, it is more efficient to simply use the XmlTextReader if validation is not required.
As an alternative to creating the XmlSchemaCollection on the fly, as shown in Listing 13.2, you can create a stand-alone XmlSchemaCollecton object and, when needed, pass it to the Add method of the Schemas property. In this way, the schemas are only loaded once. This allows multiple documents to be loaded without re-loading and re-parsing the schemas.
Using an XML Writer
Not only does System.Xml provide streamed access for reading documents, it also includes the XmlWriter class for high-performance output. Once again, the XmlWriter class is the base class, while you typically work with the XmlTextWriter derived class.
Basically, the XmlTextWriter includes properties that allow you to control how the XML will be written in terms of its formatting and namespace usage, methods analogous to other stream writers discussed in Chapter 11 such as Flush and Close, and a bevy of Write methods that add text to the output stream. The important members for the XmlTextWriter class are shown in Table 13.3.
Table 13.3 Important XmlTextWriter members.
Member |
Description |
Formatting |
When set to Formatting.Indented, specifies that output will be formatted according to the Indentation and IndentChars properties |
Indentation |
Specifies how many IndentChar characters to write out for each level in the hierarchy. Default is 2 |
IndentChars |
Specifies which character to use for indentation |
Namespaces |
When set to True, namespaces are supported |
QuoteChar |
Specifies which character to use to quote attribute values |
WriteState |
Set to one of the WriteState enumeration constants (Attribute, Closed, Content, Element, Prolog, Start) |
Close |
Closes the XmlTextWriter and the underlying stream |
Flush |
Flushes whatever is in the buffer for the XmlTextWriter and the underlying stream |
LookupPrefix |
Returns the closest prefix defined in the current namespace scope |
WriteAttributes |
Writes out all the attributes found at the current position in the XmlReader |
WriteAttributeString |
Writes an attribute with the specified value |
WriteBase64, WriteBinHex, WriteChars, WriteString |
Write the given argument to the underlying stream using the appropriate data type |
WriteCData, WriteComment, WriteDocType, WriteEntityRef, WriteProcessingInstruction, WriteWhitespace, WriteStartDocument, WriteEndDocument |
Write out particular XML elements as implied by their names |
WriteStartAttribute, WriteEndAttribute |
Write an attribute to the document |
WriteStartElement, WriteEndElement, WriteFullEndElement |
Write an element to the document |
WriteRaw |
Writes the given string or character array to the underlying stream |
The interesting aspect of the XmlTextWriter class is that it abstracts all of the formulation and writing of tags that would typically have to be done if you were creating an XML document manually. In fact, the XmlTextWriter is smart in that it keeps track of the hierarchy of the document in order to automatically providing ending tags through methods such as WriteEndElement and WriteEndDocument. The result is a programming model that not only performs very well, but is also extremely simple to use.
To illustrate the use of the XmlTextWriter class, consider the WriteXml method shown in Listing 13.3.
Listing 13.3. Writing XML. This simple method accepts a text file as an argument and writes it out as an XML document.
Public Sub WriteXml(ByVal pFileName As String) Dim fs As FileStream Dim sReader As StreamReader Dim strLine As String Dim strStudentID, strFName, strLName, strOrg As String Dim tw As XmlTextWriter Try fs = New FileStream(pFileName, FileMode.Open, FileAccess.Read) sReader = New StreamReader(fs) tw = New XmlTextWriter(pFileName & ".xml", _ New System.Text.UTF8Encoding()) tw.Formatting = Formatting.Indented tw.Indentation = 4 ' Write out the header information tw.WriteStartDocument() tw.WriteComment("Produced from " & pFileName & " on " & Now.ToString) tw.WriteStartElement("stud", "Students", "http://www.quilogy.com/education") ' Loop through the input file strLine = sReader.ReadLine Do While Not strLine Is Nothing strStudentID = Trim(Mid(strLine, 1, 5)) strFName = Trim(Mid(strLine, 13, 25)) strLName = Trim(Mid(strLine, 64, 25)) strOrg = Trim(Mid(strLine, 115, 25)) ' Now write the Xml tw.WriteStartElement("Student") tw.WriteAttributeString("StudentID", strStudentID) tw.WriteStartElement("Name") tw.WriteAttributeString("First", strFName) tw.WriteAttributeString("Last", strLName) ' Close the Name tag tw.WriteEndElement() If strOrg.Length = 0 Or strOrg.Equals("NULL") Then ' Skip Else tw.WriteElementString("Organization", strOrg) End If ' Close the Student tag tw.WriteEndElement() strLine = sReader.ReadLine Loop ' Finish off the document ' Close the Students tag tw.WriteEndDocument() ' Close the files tw.Flush() tw.Close() sReader.Close() Catch e As IOException ' Catch initial io errors LogMessage(pFileName, e.Message) Catch e As XmlException LogMessage(pFileName & ".xml",e.Message,e.LineNumber, e.LinePosition) End Try End Sub
In this example, you'll notice that a text file containing student information is passed into the WriteXml method and is opened using a standard FileStream object. The XmlTextWriter is initialized with the name of the XML document to write to in addition to the encoding to use. The overload constructor also accepts Stream or TextWriter objects.
As indicated in Table 13.3, the formatting for the document is specified using the Formatting and Indentation properties. The header of the document, along with a comment, is then written using the WriteStartDocument and WriteComment methods. The WriteStartElement method writes out the Students element and includes a namespace declaration. As implied by the name, this method writes out the beginning of the tag but does not yet close it.
The Do Loop reads through each line of the text file (which in this case is a fixed-format file) and parses its contents into four variables that include the student's ID, name, and organization. To write out the meat of the data, a Student element is created using WriteStartElement and its attribute using WriteAttributeString. Note that both of these methods can also accept namespace and prefix information. A child element to contain the name is then created by invoking WriteStartElement again. Its attributes are then also created. At this point, two elements have been created but have not been closed. The WriteEndElement method determines the current context and writes the appropriate ending tag (either a "/>" or a full ending tag that includes the element name). In this case, it will simply close the Name tag since it does not contain a value.
If the organization is present, the WriteElementString method is used to write a complete element including its closing tag along with the value passed to the method. The Student tag is then closed once again using the WriteEndElement method.
Once the input file has been exhausted, the XML document is finished off by writing the ending tag for the Students element using WriteEndDocument. This method also tracks the current context and closes any open elements. The file is closed by calling Flush followed by Close, as is typical of stream writers.