Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Team Foundation Server Hosting
Search :       Advanced Search »
Home » ADO.NET & Database » Understanding the DOM Implementation

Understanding the DOM Implementation

In this article I will explain you about DOM implementation in C# and .NET.

Author Rank :
Page Views : 4229
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Mindcracker MVP Summit 2012
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


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

The XmlNode class

The XmlNode class is an abstract base class. It represents a tree node in a document. This tree node can be the entire document. 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 children nodes of current node. You can treat an entire document as node and use ChildNodes to get all nodes in a document. 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 next sibling node of the current node. Other common properties are Attributes, Base URI, InnerXml, Inner Text, Item Node Type, Name, Value, and so on.

You can use the CreateNavigator method of this class to create an Xpath Navigator object, which provides fast navigation using xpath. The Appendchilds, InsertAfter, and InsertBefore methods add nodes to the document. The Remove All, Remove Child, and ReplaceChild methods remove or replace document nodes, respectively. You'll implement these methods and properties in the example after discussing a few more classes.

The xml Document Class

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

Loading a Document

DOM is a cache tree representation of an XML document. The Loads 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. This code example loads the document books.xml from a string:


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


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

        Dim xmlDoc As New XmlDocument()
        Dim reader As 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 methods saves a document to a specified location. The Save method takes a paramenter of XmlWriter, XmlTextWriter or string type:


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

        Dim writer As New XmlTextWriter("c:\domtest.Xml", Nothing)
        writer.Formatting = Formatting.Indented
        xmlDoc.Save(writer)


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


        xmlDoc.Save("c:\domtest. Xml")
        xmlDoc.Save(Console.Out)


The XmlDocumentFragment class

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

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

Listing 6-16. XmlDocumentFragment sample


        'open an XML file
        Dim filename As String = "c:\books.xml"
        Dim xmlDoc As New XmlDocument()
        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)


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

Listing 6-17. Appending in an XML document fragment

        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)


The Xml Element Class

An XmlElement class object represents an element in a document. This class comes from the XmlLinkedNode class, which comes from XmlNode (see figure 6-8).

Figure-6.8.gif

Figure 6-8. xml element inheritance

The XmlLinkedNode has two useful properties: NextSibing 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 element (see table 6-7).

Table 6-7. Some xml element 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, RemoveAttribute

Removes all attributes and specified attributes from an element respectively

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

SetAttribute Node

Adds a new xml Attribute


In the later examples. I'll 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 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-18 shows an example of adding two nodes to a document.

Listing 6-18. Adding nodes to a document


        Dim xmlDoc As 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 a First Name to the documentt
        node1 = xmlDoc.CreateElement("First Name")
        node1.InnerText = "Mahesh"
        xmlDoc.DocumentElement.AppendChild(node1)
        xmlDoc.Save(Console.Out)

Getting the Root Node

The DocumentElement method of the XmlDocument class (inherited from XmlNode) returns the root node of a document. The following example shows you how to get the root of a document (see listing 6-19).

Listing 6-19. Getting root node of a document


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

Removing and Replacing Nodes

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

Listing 6-20. Removing all item of a node


    Shared Sub Main(ByVal args() As String)
        ' 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 Remove All")
        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 Sub


Note: You can apply the Remove All method on the books.xml files to delete all the data, but make sure to have backup copy first!

Listing 6-21 shows how to delete all the item of books. Xml

Listing 6-21.CallingRemoveAll for books.Xml


    Public Shared Sub Main()
        Dim filename As String = "c:\ books.Xml"
        Dim xmlDoc As 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 Sub

The ReplaceChild method replaces an old child with a new child node. In Listing 6-22, ReplaceChild replaces root Node; Last Child with xmlDocFrag.

Listing 6-22 Replace Child method sample


        Dim filename As String = "C:\books.xml"
        Dim xmlDoc As 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)

Inserting XML Fragments into an XML Document

As discussed previously, the XmlNode class is useful for navigating through the nodes of a document. 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 of where you want to insert the fragment. As discussed earlier in this article, you create an XmlDocumentFragment class object by using the CreateDocumentFragment method of the XmlDocument class. Listing 6-23 inserts an XML fragment into a document after the current node using InsertAfter.

Listing 6-23. Inserting an XML fragment into a document

        Dim xmlDoc As New XmlDocument()
        xmlDoc.Load("C:\\ books.Xml")
        Dim xmlDocFragment As XmlDocumentFragment = xmlDoc.CreateDocumentFragment()
        xmlDocFragment.InnerXml = "< Fragment >< Some Data> Fragment Data</ Some Data> </ Fragment>"
        Dim aNode As XmlNode = xmlDoc.DocumentElement.FirstChild
        aNode.InsertAfter(xmlDocFragment, aNode.LastChild)
        xmlDoc.Save(Console.Out)


Adding Attributes to a Node

You use the SetAttributeNode method of xmlElement to add attributes to an element, which is a Node. The XmlAttribute represents an XML attribute. You create an instance of XmlAttribute by calling CreateAttribute of XmlDocument. After that you call an xml Element's Set Attribute method to set the attribute of an element. Finally, you append this new item to the document (see listing 6-24).

Listing 6-24. Adding a node with attributes

        Dim xmlDoc As 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)

Conclusion

Hope this article would have helped you in Understanding the DOM Implementation. See other articles on the website also for further reference.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Dinesh Beniwal
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
DevExpress Free UI Controls
Become a Sponsor
 Comments
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.