The Document Object Model Implementation

only for RuBoard

The Document Object Model (DOM) is the representation of an XML document as a set of objects that can manipulate the structure and contents of the document. By now, you should be aware of this concept. Chapter 2 introduced the DOM, Chapter 3 gave examples of how to work with the DOM, and Chapter 5 went into detail about the DOM and how it is used with MSXML. This section details how the DOM is represented in .NET.

The DOM implementation in .NET is like the MSXML parser. The entire structure is loaded into memory, and the document's parts can be accessed as a set of linked nodes. These nodes are manipulated by using the XmlNode class and its derived classes. Refer to Figure 6.5, which shows the different implementations of the XmlNode abstract class. Notice that one of the classes derived from XmlNode is the XmlDocument class: This class forms the basis for the DOM implementation in .NET.

The XmlDocument Class

Loading the entire document into memory provides many benefits. For example, it's easy to navigate through the DOM, adding, updating, and removing nodes within it. We discussed how this functionality comes at a price: Loading the entire document requires more memory than reading the document as a stream, compounded by the fact that each user accessing the document creates their own object instance in memory. However, this is an acceptable tradeoff for most scenarios where the XML being loaded is relatively small.

Consider the Usage in Your Designs

As with all distributed application designs, you need to consider whether you need the flexibility of updating, adding, and removing nodes with the XmlDocument class, or if you only need to read the document with an XmlReader class.

Looking at the XmlDocument class shows that the methods and properties of the class are similar to those of the MSXML parser. Table 6.6 shows the properties of the XmlDocument class, Table 6.7 shows its methods, and Table 6.8 shows its events.

Table 6.6. Properties of the XMLDocument Class

Property Name

Description

Attributes

Gets an XmlAttributeCollection that contains the attributes of this node.

BaseURI

Gets the base URI of the current node. Indicates from where the node was loaded.

ChildNodes

Gets all the children of the current node.

DocumentElement

Retrieves the root element of the XML document as an XmlElement object.

DocumentType

Gets the <!DOCTYPE..> declaration, if one exists as an XmlDocumentType object.

FirstChild

Gets the first child of the current node.

HasChildNodes

Returns a Boolean that indicates if the current node has child nodes.

Implementation

Returns the XmlImplementation object for the XML document.

InnerText

Gets or sets the concatenated values of the node and all its children.

InnerXml

Gets or sets the markup that represents the children of the current node.

IsReadOnly

Returns a Boolean that indicates whether the current node is read only.

Item

Returns the specified child element. This is the indexer in C# for the XmlDocument class.

LastChild

The last child of the node.

LocalName

Gets the name of the node without the namespace prefix.

Name

Gets the qualified name of the node.

NamespaceURI

Returns the namespace URI of the current node.

NameTable

Returns the XmlNameTable associated with this implementation.

NextSibling

Returns the node following this node at the same level in the document hierarchy.

NodeType

Returns an XmlNodeType enumeration member that represents this node's type.

OuterXml

Gets the XML markup that represents the current node and its children. This is similar to InnerXml , except the current node is also returned.

OwnerDocument

Gets the XmlDocument to which the current node belongs.

ParentNode

Gets the parent of the current node. If the node has been created but not added to the tree, this returns a null reference in C#, or nothing in Visual Basic .NET.

Prefix

Gets or sets the namespace prefix for the current node.

PreserveWhitespace

Gets or sets a Boolean that indicates if white space would be preserved or stripped.

PreviousSibling

Gets the node previous to this node at the same level in the document hierarchy.

Value

Gets or sets the value of the current node.

XmlResolver

Sets the XmlResolver to use for resolving external resources.

Table 6.7. Methods of the XMLDocument Class

Method Name

Description

AppendChild

Adds the specified node to the end of the list of children of the current node.

Clone

Creates a duplicate of the current node.

CloneNode

Similar to Clone , but accepts a deep Boolean parameter that indicates if the subtree should be duplicated also.

CreateAttribute

Creates an XmlAttribute node with the specified name.

CreateCDATASection

Creates an XmlCDATASection that contains the specified data.

CreateComment

Creates an XmlComment that contains the data specified.

CreateDocumentFragment

Creates an empty XmlDocumentFragment used for tree inserts .

CreateDocumentType

Creates an XmlDocumentType object.

CreateElement

Creates an empty XmlElement . Uses the Value property to specify text data for the element or append an XmlTextNode as the element's child.

CreateEntityReference

Creates an XmlEntityReference with the specified name.

CreateNavigator

Creates an XpathNavigator for navigating this object as a DOM structure.

CreateNode

Creates an XmlNode object with the specified XmlNodeType .

CreateProcessingInstruction

Creates an XmlProcessingInstruction that contains the specified target and data. To work with the <?xml version="1.0"?> xml declaration, use the CreateXmlDeclaration method.

CreateSignificantWhitespace

Creates an XmlSignificantWhitespace node that contains only the characters &#20;, &#10;, &#13; , and &#9;.

CreateTextNode

Creates an XmlTextNode with the passed in text.

CreateWhitespace

Creates an XmlWhitespace node containing only the characters &#20;, &#10;, &#13; , and &#9; .

CreateXmlDeclaration

Creates an XmlDeclaration object with the specified values. Accepts parameters for version, encoding, and standalone.

GetElementByID

Gets the XmlElement with the specified ID attribute. If multiple matches are found, returns only the first match.

GetElementsByTagName

Returns an XmlNodeList that contains all the descendant elements with the specified name.

GetEnumerator

Enables For Each enumerations on the object.

GetHashCode

Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures, such as a hash table.

GetNamespaceOfPrefix

Retrieves the namespace URI in the closest XMLNS declaration for the given prefix.

GetPrefixOfNamespace

Retrieves the prefix in the closest XMLNS declaration for the given URI.

GetType

Gets the type of the current instance.

ImportNode

Imports a node from an external document to the current document.

InsertAfter

Inserts the node immediately after the specified reference node.

InsertBefore

Inserts the node immediately before the specified reference node.

Load

Loads the XML data. Sources for the XML data include a URL, a stream, a text reader, and an XmlReader .

LoadXml

Loads the XML document from the string parameter.

Normalize

Puts all XmlText nodes in the full depth of the subtree underneath this XmlNode into a normal form where only markup (for example, tags, comments, processing instructions, CDATA sections, and entity references) separates XmlText nodes; that is, no adjacent XmlText nodes exist.

PrependChild

Adds the specified node as the first child of the current node.

ReadNode

Creates an XmlNode object based on the information in the XmlReader . The reader must be positioned on a node or attribute. If positioned on an element node, it advances the reader to the next position. If positioned on an attribute, it does not advance the reader.

RemoveAll

Removes all children and/or attributes of the current node.

RemoveChild

Removes the specified child node associated with the current node.

ReplaceChild

Removes the old child node and replaces it with the new child node.

Save

Saves the XML document to the specified location.

SelectNodes

Selects an XmlNodeList of nodes that match the specified XPath expression.

SelectSingleNode

Selects an XmlNode that matches the specified XPath expression. If more than one match is found, only the first match is returned.

Supports

Tests if the DOM implementation supports a specific feature.

ToString

Returns a string that represents the current object.

WriteContentTo

Saves the contents of the XmlDocument node to the specified XmlWriter .

WriteTo

Saves the XmlDocument node to the specified XmlWriter .

Table 6.8. Events of the XMLDocument Class

Event Name

Description

NodeChanged

The value of a node belonging to this document has been changed.

NodeChanging

The value of a node belonging to this document is about to change.

NodeInserted

A node belonging to this document has been inserted into another node.

NodeInserting

A node belonging to this document is about to be inserted into another node.

NodeRemoved

A node belonging to this document has been removed.

NodeRemoving

A node belonging to this document is about to be removed.

Populating an XmlDocument

Several methods for loading an XmlDocument object with data exist. You've already seen examples of using a file to load the XmlDocument earlier in this chapter. You can also specify a string to populate it with data, as shown here:

 <%@ Import Namespace="System.Xml"%>  <%@ Import Namespace="System.Text"%>  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >  <HTML>       <HEAD>            <title>WebForm1</title>            <script language="C#" runat="server">            private void Page_Load(object sender, System.EventArgs e)            {                StringBuilder sb = new StringBuilder();              sb.Append("<DATA xmlns=\"urn:foo:bar\">");              sb.Append("<PERSON name=\"Carson Allen Evans\"/>");                 sb.Append("<PERSON name=\"Deanna Evans\">Hello, Wife</PERSON>");                 sb.Append("</DATA>");                 XmlDocument doc = new XmlDocument();                 doc.LoadXml(sb.ToString());                 TextBox1.Text = doc.OuterXml;           }            </script>    </HEAD>    <body>         <form runat="server">          <asp:TextBox id="TextBox1" runat="server" TextMode="MultiLine" Width="473px" graphics/ccc.gif Height="447px"></asp:TextBox>         </form>       </body>  </HTML> 

This example uses a StringBuilder to build a string representation of the XML document. The XmlDocument object is then populated by calling the LoadXml method. You could also use an XmlTextReader to populate the XmlDocument because an XmlTextReader is an implementation of the XmlReader class.

Recall that you can use the XmlTextReader to access secured documents on external resources. Using the XmlTextReader as the source for the XmlDocument is a good choice in this situation.

Now that you have seen how to get data into the XmlDocument , take a look at how to navigate through its contents.

only for RuBoard


XML and ASP. NET
XML and ASP.NET
ISBN: B000H2MXOM
EAN: N/A
Year: 2005
Pages: 184

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