Home > Articles

0672321300

Like this article? We recommend

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020