Navigating the Tree

MSXML 5.0 SDK

Microsoft XML Core Services (MSXML) 5.0 for Microsoft Office - DOM Developer's Guide

Navigating the Tree

The Document Object Model (DOM) treats the contents of documents as a collection of nodes of various types. Some nodes contain other nodes, or groups of nodes, building a structure commonly referred to as the document tree. Programs that access or manipulate the information stored in XML documents through the DOM must navigate this tree structure.

From an IXMLDOMNode object, you can navigate directly to its parent node (parentNode), children (childNodes, firstChild, lastChild), siblings (previousSibling, nextSibling), or the document object to which the node belongs (ownerDocument). If the node is of type element, attribute, or entityReference, you can call the definition property to navigate to the schema definition of the node. In addition, if the node is of type element, processingInstruction, documentType, entity, or notation, you can navigate to the attributes on the node using the attributes property.

The following code tests to see if the elem1 element has any element children. If so, it navigates from elem1 to that element's first child. The text of that first child is then changed to "I'm the first child of elem1".

if (elem1.hasChildNodes == true && elem1.firstChild.nodeTypeString == "element")
  elem1.firstChild.text = "I'm the first child of elem1"

To navigate to nodes other than the first or last sibling, you can start from the first or last child and use the previousSibling or nextSibling methods to move forward or backward through the list.

wantedNodeCount=2
currentNode=1
set wantedNode=elem1.firstChild
Do While currentNode<wantedNodeCount
  set wantedNode=wantedNode.nextSibling
  currentNode=currentNode+1
Loop

The following is an example in Microsoft® JScript®.

wantedNodeCount=2;
currentNode=1;
wantedNode=elem1.firstChild;
while (currentNode<wantedNodeCount) {
  wantedNode=wantedNode.nextSibling;
  currentNode++;
}

In either case, the variable wantedNode contains the desired node, and can be used for other processing or navigation. With a few additional comparisons, you can use techniques like these to find nodes that meet specific type and content criteria. If you prefer to walk through the list of child nodes using numeric references, use the IXMLDOMNodeList object returned by the childNodes property.

It is also possible to navigate to other nodes in the tree using the selectNodes and selectSingleNode methods. These methods take an XML Path Language (XPath) expression as an argument and return the node or nodes that match that query. For more information about XPath, see XPath Syntax.

See Also

attributes Property | childNodes Property | definition Property | firstChild Property | lastChild Property | nextSibling Property | ownerDocument Property | parentNode Property | previousSibling Property | selectNodes Method | selectSingleNode Method