XML Programming in the .NET Framework


For working with XML in the .NET Framework, you mainly work with the classes in the System.Xml namespace. With these classes, you can read and write to XML documents, traverse and change the values of the elements in an XML document, validate the document, and so on. This section therefore discusses some important classes in the System.Xml namespace and provides examples on how to use them.

Note

For importing XML into a database or saving a database table into XML, you can use the System.Data.DataSet class.

To read XML, you use the reader classes in the System.Xml namespace. There is the abstract XmlReader class with its three child classes: XmlNodeReader, XmlTextReader, and XmlValidatingReader. Of these, the XmlTextReader class provides the fastest access to XML data. However, you can only use this class to read XML in a noncached, forward-only direction. An important class you can use to validate an XML document is the XmlValidatingReader class.

For writing to XML documents, you use the writer classes in the System.Xml namespace. There is the abstract XmlWriter class and its child class, XmlTextWriter. XmlWriter represents a writer for generating streams or files containing XML data. Like the XmlTextReader, XmlWriter and XmlTextWriter work only in a non-cached, forward-only direction.

When working with XML, you often want to access an individual node in the document—for example, when you need to traverse nodes in an XML document. For this purpose, you use the XmlNode class. As the name implies, XmlNode represents a node in an XML document.

Also, everyone working with XML in the .NET Framework needs to be familiar with the XmlDocument class, which represents an XML document. This class directly derives from XmlNode and has one child class: XmlDataDocument.

Reading XML

An important class that is frequently used for reading XML documents is the XmlTextReader class. Constructing an instance of this class is easy because XmlTextReader provides 13 constructors from which to choose. For example, you can pass a System.IO.Stream or the URL of the XML document you want to read.

You can find the complete list of members of this class in the class library reference of the .NET Framework Software Development Kit (SDK) documentation; however, the following are some of the important properties:

  • Depth: The depth of the node.

  • EOF: Indicates if the end of file has been reached.

  • HasValue: Indicates whether the node can have a value.

  • IsEmptyElement: Indicates whether the current node is an empty element.

  • LineNumber: Returns the current line number.

  • Name: The name of the node.

  • NodeType: The type of the node. Its value is one of the members of the System.Xml.XmlNodeType enumeration: Attribute, CDATA, Comment, Document, DocumentFragment, DocumentType, Element, EndElement, EndEntity, Entity, EntityReference, None, Notation, ProcessingInstruction, SignificantWhiteSpace, Text, Whitespace, and XmlDeclaration.

  • Value: The node's text value.

The XmlTextReader class has a number of methods; however, the most important method is Read, which you use to read the next node in the document. When Read is called, the node name is copied into the Name property and the node value is copied into the Value property. The Read method returns True if the next node was read successfully and False if it has reached the last node.

Listing 2-9 uses the XmlTextReader class to read an XML document's nodes in sequence and displays the name and the value of an element node.

Listing 2-9: Reading an XML Document

start example
 Imports System.Xml Dim xmlReader As XmlTextReader Try   xmlReader = New XmlTextReader("test.xml")   While xmlReader.Read()     If xmlReader.NodeType = XmlNodeType.Element Then       System.Console.WriteLine(xmlReader.Name & " : ")     End If     If xmlReader.NodeType = XmlNodeType.Text Then       System.Console.WriteLine(xmlReader.Value)     End If   End While Catch ex As Exception End Try If Not xmlReader Is Nothing Then   xmlReader.Close() End If 
end example

In Listing 2-9, you first open an XML document called test.xml. Then, you read each node in the XML document by repeatedly calling the Read method of the XmlTextReader class until it returns False.

Validating XML Documents

If you read the "A Brief Theory on XML" section earlier in the chapter, you know that being able to maintain data integrity is one reason why XML survives today. The mechanism for checking the data integrity through validating a document is solid in XML, and the System.Xml namespace has the XmlValidatingReader class that makes validating XML documents a piece of cake.

To use the XmlValidatingReader class, you first construct an instance of it and keep calling its Read method. This method throws a System.Xml.XmlException when it encounters an invalid line. You can then retrieve the message from the exception to find out what makes the document invalid. The XmlValidatingReader class has similar properties and methods to XmlTextReader. However, XmlValidatingReader does not have a constructor that accepts a System.IO.Stream object. Instead, you can pass an XmlReader object.

Listing 2-10 presents code that validates an XML document.

Listing 2-10: Validating an XML Document

start example
 Imports System.Xml Dim xmlReader As XmlTextReader Dim xmlValReader As XmlValidatingReader Try   xmlReader = New XmlTextReader("test.xml")   xmlValReader = New XmlValidatingReader(xmlReader)   While xmlValReader.Read()   End While   System.Console.WriteLine("document validated") Catch ex As Exception     System.Console.WriteLine(ex.ToString()) End Try If Not xmlValReader Is Nothing Then   xmlValReader.Close() End If 
end example

Writing to XML Documents

You use the System.Xml.XmlTextWriter class to write to XML documents. This class has properties and methods that make it convenient to write to an XML document. The following are some important properties:

  • Formatting: Indicates how the document is formatted. It can accept one of the two members of the System.Xml.Formatting enumeration: Indented or None.

  • Indentation: Determines how many IndentChar characters to be written for each level in the node hierarchy.

  • IndentChars: The character for indenting. The default is a space.

When working with the XmlTextWriter class, you will often use the following methods: WriteStartDocument, WriteEndDocument, WriteComment, WriteStartAttribute, WriteEndAttribute, WriteStartElement, WriteEndElement, and WriteString. All these methods are self-explanatory.

Listing 2-11 presents code that writes to an XML document using the XmlTextWriter class.

Listing 2-11: Writing to an XML Document

start example
 Imports System.Xml Dim xmlWriter As XmlTextWriter Try   xmlWriter = New XmlTextWriter("test2.xml", Nothing)   xmlWriter.WriteStartDocument()   xmlWriter.Formatting = Formatting.Indented   xmlWriter.Indentation = 4   xmlWriter.WriteStartElement("books")   xmlWriter.WriteStartElement("book")   xmlWriter.WriteAttributeString("id", "1")   xmlWriter.WriteElementString("author", "Holzner, Charles")   xmlWriter.WriteElementString("title", _     "English-Japanese Dictionary")   xmlWriter.WriteElementString("price", "59.95")   xmlWriter.WriteEndElement()   xmlWriter.WriteEndElement()   xmlWriter.WriteEndDocument() Catch ex As Exception Finally   xmlWriter.Close() End Try 
end example

When run, this is the resulting XML document:

 <?xml version="1.0"?> <books>     <book >         <author>Holzner, Charles</author>         <title>English-Japanese Dictionary</title>         <price>59.95</price>     </book> </books> 

Traversing XML Nodes

XML is a hierarchical data structure. As such, it is often desirable to be able to traverse through each individual node in an XML document. You can easily do this in the .NET Framework thanks to the System.Xml.XmlNode and the System.Xml.XmlDocument classes.

The XmlNode class represents a node in an XML document. As a node can have child nodes, the XmlNode class is equipped with the ChildNodes property that returns a System.Xml.XmlNodeList containing all the child nodes of the current node. Then, it also has the FirstChild property from which you can obtain the first child node. You can obtain the node name from the Name property and the node's value from the Value property. You can find a complete list of properties in the documentation.

As to the methods, the following are some important methods of the XmlNode class:

  • AppendChild: Adds a node to the end of the list of child nodes

  • InsertAfter: Inserts a node right after a reference node

  • InsertBefore: Inserts a node right before a reference node

  • RemoveChild: Removes a child node

The XmlDocument class represents an XML document. The following are some of the properties of the XmlDocument class:

  • DocumentElement: Returns the root XmlDocument for the document

  • Name: The name of the node

  • NodeType: The type of the node

The following are some of the methods in the XmlDocument class, all of which are self-explanatory: CreateAttribute, CreateComment, CreateElement, CreateNode, Load, LoadXml, ReadNode, and Save.

As an example, consider Listing 2-12, which you can use to traverse an XML document and display its nodes' names and values. Listing 2-13 shows the input that produces the output shown in Listing 2-14.

Listing 2-12: Traversing Nodes in an XML Document

start example
 Imports System.Xml Dim xmlDocument As New XmlDocument() Try   xmlDocument.Load("test.xml")   DrawNode(xmlDocument.DocumentElement, 1) Catch ex As Exception End Try . . . Sub DrawNode(ByVal node As XmlNode, ByVal level As Integer)   'Draw only if node.NodeType is Element or Text   'Draw the line   System.Console.Write(New String("-"c, level * 2))   'If node.NodeType = Text, we don't want to display   'the node.Name   If node.NodeType = XmlNodeType.Element Then     System.Console.Write(node.Name)   End If   System.Console.WriteLine(node.Value)   If (node.HasChildNodes) Then     node = node.FirstChild     While Not IsNothing(node)       If node.NodeType = XmlNodeType.Element Or _       node.NodeType = XmlNodeType.Text Then       DrawNode(node, level + 1)     End If     node = node.NextSibling End While   End If End Sub 
end example

Listing 2-13: The Input

start example
 <?xml version="1.0" standalone="yes"?> <!DOCTYPE products [ <!ELEMENT products (product)*> <!ELEMENT manufacturer (#PCDATA)> <!ELEMENT product (name, product_id)> <!ELEMENT name (#PCDATA)> <!ELEMENT product_id (#PCDATA)> ]> <products>   <product>     <name>ChocChic</name>     <product_id>12</product_id>   </product>   <product>     <name>Waftel Chocolate</name>     <product_id>15</product_id>   </product> </products> 
end example

Listing 2-14: The Output

start example
 --products ----product ------name --------ChocChic ------product_id --------12 ----product ------name --------Waftel Chocolate ------product_id --------15 
end example

Listing 2-12 features the recursive DrawNode subroutine to draw all the element nodes. When called, this method is passed the root element of the XML document and a level of 1.

For each node, the DrawNode draws a line consisting of a number of hyphen characters. The number of hyphen characters is proportional to the value of level.

For each node whose type is Element, the node's name is output to the console:

 'If node.NodeType = Text, we don't want to display 'the node.Name If node.NodeType = XmlNodeType.Element Then   System.Console.Write(node.Name) End If System.Console.WriteLine(node.Value) 

Then, it checks if the current node has child nodes. If it has, the node is assigned the first child of children:

 If (node.HasChildNodes) Then   node = node.FirstChild 

And then, for each child node that is an element, it calls the DrawNode method again and increments the level:

 While Not IsNothing(node)   If node.NodeType = XmlNodeType.Element Or _     node.NodeType = XmlNodeType.Text Then     DrawNode(node, level + 1)   End If   node = node.NextSibling End While 

Now that you know how to manipulate XML documents in .NET, it is time to discuss MDI applications.




Real World. NET Applications
Real-World .NET Applications
ISBN: 1590590821
EAN: 2147483647
Year: 2005
Pages: 82

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net