Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
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:
Total page views :  3072
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor


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.


Login to add your contents and source code to 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.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
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.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Become a Sponsor
 Comments

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.