Understanding the DOM Implementation


Microsoft .NET supports the W3C DOM Level 1 and DOM Level 2 Core specifications. The .NET Framework provides DOM implementation through many classes; XmlNode and XmlDocument are two of them. Using these two classes, you can easily traverse through XML documents in the same manner as you do in a tree.

Using the XmlNode Class

The XmlNode class is an abstract base class; it represents a node of an XML document. Because an XML document starts with a root node, the XmlNode class that corresponds to the root node represents the entire XML document's nodes. An XmlNode object can represent a node at any level. This class defines enough methods and properties to represent a document node as a tree node and traverse though it. It also provides methods to insert, replace, and remove document nodes.

The ChildNodes property returns all the child nodes of the current node. You can treat an entire document as a node and use ChildNodes to get all the nodes in a document. Also, you can use the FirstChild, LastChild, and HasChildNodes triplet to traverse from a document's first node to the last node. The ParentNode, PreviousSibling, and NextSibling properties return the parent and previous/next sibling nodes of the current node. Other common properties are Attributes, BaseURI, InnerXml, InnerText, Item, NodeType, Name, Value, and so on.

You can use the CreateNavigator method of this class to create an XPathNavigator object, which provides fast navigation using XPath. The AppendChild, InsertAfter, and InsertBefore methods add nodes to the document. The RemoveAll, RemoveChild, and ReplaceChild methods remove or replace document nodes, respectively. You'll implement these methods and properties later in this chapter.

Using the XmlDocument Class

The XmlDocument class represents an XML document. Because it's derived from the XmlNode class, it supports all tree traversal, insert, remove, and replace functionality. In spite of XmlNode functionality, this class contains many useful methods.

The DOM is a cached tree representation of an XML document. The Load and LoadXml methods of this class load XML data and documents, and the Save method saves a document.

The Load method can load a document from a string, stream, TextReader, or XmlReader. The following code loads the document books.xml from a string:

 Dim xmlDoc As XmlDocument = New XmlDocument()     Dim filename As String = "C:\\books.xml"     xmlDoc.Load(filename) xmlDoc.Save(Console.Out) 

The following example uses the Load method to load a document from an XmlReader:

 Dim xmlDoc As XmlDocument = New XmlDocument()     Dim reader As XmlTextReader _     = New XmlTextReader("C:\\books.xml")     xmlDoc.Load(reader)     xmlDoc.Save(Console.Out) 

The LoadXml method loads a document from the specified string. For example:

 xmlDoc.LoadXml("<Record> write something</Record>"); 

Saving a Document

The Save method saves a document to a specified location. The Save method takes a parameter of XmlWriter, XmlTextWriter, or a string type:

  Dim xmlDoc As XmlDocument = New XmlDocument() Dim filename As String = "C:\\books.xml" xmlDoc.Load(filename) Dim writer As XmlTextWriter = _ New XmlTextWriter("C:\\domtest.xml", Nothing) writer.Formatting = Formatting.Indented xmlDoc.Save(writer) 

You can also use a filename or Console.Out to save the output as a file or on the console:

 xmlDoc.Save("C:\\domtest.xml") xmlDoc.Save(Console.Out) 

Using the XmlDocumentFragment Class

Usually, you would use the XmlDocumentFragment class when you need to insert a small fragment of an XML document or node into a document. This class also comes from the XMLNode class and has the same tree node traverse, insert, remove, and replace capabilities.

You usually create this class instance by calling XmlDocument's CreateDocumentFragment method. The InnerXml property represents the children of this node. Listing 6-10 shows an example of how to create XmlDocumentFragment and load a small piece of XML data using its InnerXml property.

Listing 6-10: The XmlDocumentFragment Sample

start example
 Dim xmlDoc As XmlDocument = New XmlDocument()     Dim filename As String = "C:\\books.xml"     xmlDoc.Load(filename)     'Create a document fragment.     Dim docFrag As XmlDocumentFragment = xmlDoc.CreateDocumentFragment()     'Set the contents of the document fragment.     docFrag.InnerXml = "<Record> write something</Record>"     'Display the document fragment.     Console.WriteLine(docFrag.InnerXml) 
end example

You can use XmlNode methods to add, remove, and replace data. Listing 6-11 appends a node in the document fragment.

Listing 6-11: Appending in an XML Document Fragment

start example
 Dim doc As XmlDocument = New XmlDocument() doc.LoadXml("<book genre='programming'>" & _         "<title>ADO.NET Programming</title>" & _         "</book>") ' Get the root node Dim root As XmlNode = doc.DocumentElement ' Create a new node. Dim newbook As XmlElement = doc.CreateElement("price") newbook.InnerText = "44.95" 'Add the node to the document. root.AppendChild(newbook) doc.Save(Console.Out) 
end example

Using the XmlElement Class

An XmlElement class object represents an element in a document. This class inherits from the XmlLinkedNode class, which inherits from the XmlNode, as shown in Figure 6-4.


Figure 6-4: The XmlElement class inheritance

The XmlLinkedNode has two useful properties: NextSibling and PreviousSibling. As their names indicate, these properties return the next and previous nodes of an XML document's current node.

The XmlElement class implements and overrides some useful methods for adding and removing attributes and elements. Table 6-4 describes some of the XmlElement class methods.

Table 6-4: Some XmlElement Class Methods

METHOD

DESCRIPTION

GetAttribute

Returns the attribute value

HasAttribute

Checks if a node has the specified attribute

RemoveAll

Removes all the children and attributes of the current node

RemoveAllAttributes

Removes all attributes from an element

RemoveAttribute

Removes specified attributes from an element

RemoveAttributeAt

Removes the attribute node with the specified index from the attribute collection

RemoveAttributeNode

Removes an XmlAttribute

SetAttribute

Sets the value of the specified attribute

SetAttributeNode

Adds a new XmlAttribute

In the later examples, we show you how you can use these methods in your programs to get and set XML element attributes.

Adding Nodes to a Document

You can use the AppendChild method to add a node to an existing document. The AppendChild method takes a single parameter of XmlNode type. The XmlDocument's CreateXXX methods can create different types of nodes. For example, the CreateComment and CreateElement methods create comment and element node types. Listing 6-12 shows an example of adding two nodes to a document.

Listing 6-12: Adding Nodes to a Document

start example
  Dim xmlDoc As XmlDocument = New XmlDocument() xmlDoc.LoadXml("<Record> Some Value </Record>") ' Adding a new comment node to the document Dim node1 As XmlNode = xmlDoc.CreateComment("DOM Testing Sample") xmlDoc.AppendChild(node1) ' Adding an FirstName to the document node1 = xmlDoc.CreateElement("FirstName") node1.InnerText = "Mahesh" xmlDoc.DocumentElement.AppendChild(node1) xmlDoc.Save(Console.Out) 
end example

Getting the Root Node

The DocumentElement method of the XmlDocument class (inherited from XmlNode) returns the root node of a document. Listing 6-13 shows you how to get the root node of a document.

Listing 6-13: Getting the Root Node of a Document

start example
 Dim filename As String = "C:\\books.xml" Dim xmlDoc As XmlDocument = New XmlDocument() xmlDoc.Load(filename) Dim root As XmlElement = xmlDoc.DocumentElement 
end example

Removing and Replacing Nodes

The RemoveAll method of the XmlNode class can remove all elements and attributes of a node. RemoveChild removes the specified child only. Listing 6-14 calls RemoveAll to remove all the elements and attributes of a node.

Listing 6-14: Removing All Items of a Node

start example
 ' Load a document fragment    Dim xmlDoc As XmlDocument = New XmlDocument()    xmlDoc.LoadXml("<book genre='programming'>" & _ "<title>ADO.NET Programming</title> </book>")    Dim root As XmlNode = xmlDoc.DocumentElement    Console.WriteLine("XML Document Fragment")    Console.WriteLine("=====================")    xmlDoc.Save(Console.Out)    Console.WriteLine()    Console.WriteLine("---------------------")    Console.WriteLine("XML Document Fragment After RemoveAll")    Console.WriteLine("=====================")    'Remove all attribute and child nodes.    root.RemoveAll()    ' Display the contents on the console after    ' removing elements and attributes    xmlDoc.Save(Console.Out) 
end example

Note

You can apply the RemoveAll method on the books.xml file to delete all the data, but make sure to have a backup copy first!

Listing 6-15 shows how to delete all the items of books.xml.

Listing 6-15: Calling RemoveAll for books.xml

start example
 Dim filename As String = "C:\\books.xml" Dim xmlDoc As XmlDocument = New XmlDocument()     xmlDoc.Load(filename)     Dim root As XmlNode = xmlDoc.DocumentElement     Console.WriteLine("XML Document Fragment")     Console.WriteLine("=====================")     xmlDoc.Save(Console.Out)     Console.WriteLine()     Console.WriteLine("---------------------")     Console.WriteLine("XML Document Fragment After RemoveAll")     Console.WriteLine("=====================")     'Remove all attribute and child nodes.     root.RemoveAll()     ' Display the contents on the console after     ' removing elements and attributes     xmlDoc.Save(Console.Out) 
end example

The ReplaceChild method replaces an old child with a new child node. In Listing 6-16, ReplaceChild replaces rootNode.LastChild with xmlDocFrag.

Listing 6-16: Calling ReplaceChild

start example
 Dim filename As String = "C:\\books.xml"    Dim xmlDoc As XmlDocument = New XmlDocument()    xmlDoc.Load(filename)    Dim root As XmlElement = xmlDoc.DocumentElement    Dim xmlDocFragment As XmlDocumentFragment = xmlDoc.CreateDocumentFragment()    xmlDocFragment.InnerXml = _    "<Fragment><SomeData>Fragment Data</SomeData></Fragment>"    Dim rootNode As XmlElement = xmlDoc.DocumentElement    'Replace xmlDocFragment with rootNode.LastChild    rootNode.ReplaceChild(xmlDocFragment, rootNode.LastChild)    xmlDoc.Save(Console.Out) 
end example

Inserting XML Fragments into an XML Document

As discussed previously, the XmlNode class is useful for navigating through a document's nodes. It also provides other methods to insert XML fragments into a document. For instance, the InsertAfter method inserts a document or element after the current node. This method takes two arguments. The first argument is an XmlDocumentFragment object, and the second argument is the position where you want to insert the fragment. As discussed earlier in this chapter, you create an XmlDocumentFragment class object by using the CreateDocumentFragment method of the XmlDocument class. Listing 6-17 inserts an XML fragment into a document after the current node using InsertAfter.

Listing 6-17: Inserting an XML Fragment into a Document

start example
 Dim xmlDoc As XmlDocument = New XmlDocument()     xmlDoc.Load("c:\\books.xml")     Dim xmlDocFragment As XmlDocumentFragment = _     xmlDoc.CreateDocumentFragment()     xmlDocFragment.InnerXml = _     "<Fragment><SomeData>Fragment Data</SomeData></Fragment>"     Dim aNode As XmlNode = xmlDoc.DocumentElement.FirstChild     aNode.InsertAfter(xmlDocFragment, aNode.LastChild)     xmlDoc.Save(Console.Out) 
end example

Adding Attributes to a Node

You use the SetAttributeNode method of XmlElement to add attributes to an element, which is a node. XmlAttribute represents an XML attribute. You create an instance of XmlAttribute by calling CreateAttribute of XmlDocument. After that you call an XmlElement's SetAttribute method to set the attribute of an element. Finally, you append this new item to the document (see Listing 6-18).

Listing 6-18: Adding a Node with Attributes

start example
 Dim xmlDoc As XmlDocument = New XmlDocument()     xmlDoc.Load("c:\\books.xml")     Dim NewElem As XmlElement = xmlDoc.CreateElement("NewElement")     Dim NewAttr As XmlAttribute = xmlDoc.CreateAttribute("NewAttribute")     NewElem.SetAttributeNode(NewAttr)     'add the new element to the document     Dim root As XmlElement = xmlDoc.DocumentElement     root.AppendChild(NewElem)     xmlDoc.Save(Console.Out) 
end example




Applied ADO. NET(c) Building Data-Driven Solutions
Applied ADO.NET: Building Data-Driven Solutions
ISBN: 1590590732
EAN: 2147483647
Year: 2006
Pages: 214

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