Using the DOM In .NET C# Help

The DOM implementation in .NET supports the W3C DOM Levell and Core OOM Level 2 specifications. The DOM is implemented through the XmINodeclass, which is an abstract class that represents a node of an XML document.

There is also an XmINodeList class, which is an ordered list of nodes. This is a live list of nodes, and any changes to any node are immediately reflected in the list. XmlNodeList supports indexed access or iterative access.

The XmINodeand XmlNodeList classes make up the core of the DOM implementation in the .NET Framework The following table lists some of the classes that are based on XmINode.

The following table lists classes that extend XmlCharacterData.

The following table lists classes that extend the XmlLinkedNode

As you can see, .NET makes available a class to fit just about any XMLtype that you might encounter, Because of this, you end up with a very flexible and powerful tool set. This section won’t look at every class in detail, but you will see several examples to give you an idea of what you can accomplish.

Using the XmlDocument Class

XmlDocument and its derived class XmlDatADocument (discussed later in this chapter) are the classes that you will be using to represent the DOM in .NET Unlike XmIReader and XmIWriter, XmlDocument gives you read and write capabilities as well as random access to the OOM tree. XmlDocument resembles the DOM implementation in MSXML. If you have experience programming with MS XML, you will feel comfortable using xmlDocument.

This section introduces an example that creates an XmlDocumentobject, loads a document from disk, and loads a text box with data from the title elements. This is similar to one of the examples that you constructed in the “Using the XmlReader Class” section. The difference here is that you will be selecting the nodes you want to work with, instead of going through the entire document as in the XmlReader-based example.

Here is the code to create an XmlDocument object. Notice how simple it looks in comparison to then XmlReader example:

Note that you also add the following declaration at the module level for the examples in this section:

private XmlDocumentdoc=new XmlDocument();

If this is all that you wanted to do, using the XmIReader would have been a much more efficient way to load the text box, because you just go through the document once and then you are finished with it, This is exactly the type of work that XmlReader was designed for, However, if you wanted to revisit a node, using XmlDocument is a better way.

Here is an example of using the XPath syntax to retrieve a set of nodes from the document.

SelectNodes () returns a NodeList, or a collection of xmlNodea, Thelist contains only nodes that match the XPath statement passed in as the parametel SelectNodes, In this example, all you want’ to see fire the title nodes, If you would have made the call to select SingleNode, When you would have received a single node object that contained the first node in the xmlDocument that matched the XPath criteria.

A quick comment regarding the SelectSingleNode () method: This is an XPath unpiementation in the xmlDocurnent class. Both the SelectSi.ngleNode () and SelectNodes () methods are defined in xmlNode, which xmlDocument is based on, SeleotSlngleNode () returns an xmlNode and SelectNodes () returns an xmlNodeList, However, the System.xml.XPath namespace contains a richer XPat.h implementation, and you look at that in a later section.

Inserting Nodes

Earlier, you looked at an example using xml Textw:: iter that created a new document, The limitation was that it would not lnsert.a node into a current document. With the xmlDocument class, can do just that, Change the buttonl._Click () event handler from the last example to the following {DOMSample3in the download code):

After executing this code, you end up with the same functionality as in the previous example, but there is one additional book in the text box, The Cast of the Missing Cookie (a soon-to-be classic), If you look closely at the code, you can see that this is actually a fairly simple process. The first thing that you do is create a new book element.

XmlElement newBook= doc.CreateElement(‘book’);

CreateElement () has three overloads that allow you to specify the following:

  1. The element name
  2. The name and namspace URI
  3. The prefix, localname, and namespace

Once the element is created you need to add attributes:

newBook.SetAttribute(‘genre’, ‘Mystery’),

Now that you have the attributes created, you need to add the other element of a book.

XmlElement newTitle = doc.CreateElement(‘title’);
newTitle.lnnerText = ‘The Case of the Missing Cookie’;
newBook.App· dChild(newTitle); ,

Once again, you create a new XmlElement-based object (newTitle). Then you set the InnerText property to the title of our new classic, and append the element as a child to the book element, You repeat this for the rest of the elements in this book element. INote that you add the name element as a child to the author element, This will give you the proper nesting relationship, as in the other book elements.

Finally, you append the newBookelement to the doc. DocumentElement node. This is the same level as
all if the other book elements, You have now updated an existing document with a new element.

The last thing to do is to write the new XML document to disk. In this example, you create a new XmlTextWriter and pass it to the WriteContentTo () method, WriteContentTo () and WriteTo () book take an XmlTextWriter as a parameter, WriteContentTo () saves the current node and all of its children to the XmlTextWriter whereas writeTo ( ) just saves the current node, Because doc is an XlIIIDocument-based object, it represents the entire document and so that is what is saved. You could also use the Save () method/It ‘will always save the entire document, Save () has four overloads, You can s~ a string with the file name and path, a Stream-based object, a TextWri ter-based object, or an Xmlwriter-based object.

You also call the Close () method on XmlTextWriter to flush the internal buffers and close the file.

Figure 28-1 shows what you get when you run this example, Notice the new entry at the bottom of the list.

Figure 28-1

Figure 28-1

Earlier in the chapter, you saw how to create a document using the XmlTextWri ter class. You can also use XmlDocument.Why would you use one in preference to the other? H the data that you want streamed to XML is available and ready to write, then the XmlTextWri ter class is the best choice, However, if you need to build the XML document a little at a time, inserting nodes into various places, then creating the document with XmlDocument might be the better choice. Youcan accomplish this by changing the following line:

doc.Load(°books.xml∗) ;

to this:

//create the declaration section
XmlDeclaration newDec = doc.CreateXmlDeclaration(∗1.0∗,null,null);
//create the new root element a
XmlElement newRoot = doc.CreateElement(OnewBookstoreO);
doc .AppendChild (newRoot) ;

First, you create a new XmlDeclaration. The parameters are the version (always 1.0 for now), the encoding, and the standalone flag. The encoding parameter should be set to a string that is part of the Sys tem. Text. Encoding class if null isn’t used (null defaults to UTF-8). The standalone flag can be either yes, no, or null. H it is null, the attribute is not used and will not be included in the document.

The next element that is created will become the DocumentElement. In this case, it is called newBookstore so that you can see the difference, The rest of the code is the same as in the previous example and works in the same way, This is books Edit .XML,which is generated from the following code:

<?xml version=Ol.OO?>
<book genre=oMysteryo publicationdate=o200lo ISBN=o123456789°>
<title>The Case of the Missing C )kie</title>
<name>C. Monster</name>

You will want to use the XmlDocument class when you want to have random access to the document, or the XmlReader-based classes when you want a streaming-type model instead. Remember that there is a cost for the flexibility of the XmlNode-based XmlDocument class – memory requirements are higher and the performance of reading the document is not as good as when using XmlReaper-.There is another
way to traverse an XML document: the XPathNavigator.

Posted on October 31, 2015 in Manipulating XML

Share the Story

Back to Top
Share This