[C# – XML DOM] XPathNavigator

XPath specifies how to query XML nodes. .NET provides “System.Xml.XPath” namespace to use XPath programmatically.

 

1. “System.Xml.XPath” Namespace and Types

The “System.Xml.XPath” namespace contains the classes that define a cursor model for navigating and editing XML information items as instances of the XQuery 1.0 and XPath 2.0 Data Model

  • XPathDocument: represents XML documents to be queried with XPath. It also provides a fast and performant read-only cache for XML document processing using XSLT
  • XPathNavigator: provides a mechanism for performing XPath Queries.
  • XPathNodeIterator: provides an iterator over a selected set of nodes.

 

2. IXPathNavigable Interface

The “System.Xml.XPath.IXPathNavigable” defines only one method.

  • XPathNavigator CreateNavigator()

 

3. XPathDocument Class

XPathDocument” implements “IXPathNavigable” interface.  Surprisingly, it is not a subclass of “XmlDocument

You can create an XPathDocument object in many ways:

public XPathDocument(Stream stream)
public XPathDocument(string uri)
public XPathDocument(TextReader textReader)
public XPathDocument(XmlReader reader)

 

4. XPathNodeType Enumeration

“System.Xml.XPath.XPathNodeType” defines the XPath node types. Node types are used to select a node set from the XPathNavigator class.

public enum XPathNodeType
{
  Root, // the root node
  Element, // element node
  Attribute, // an attribute node
  Namespace, // a namespace node
  Text, // the text content of a node. Equivalent to the Document Object Model (DOM) Text and CDATA node types.
  SignificantWhitespace, // a node with white space characters and xml:space set to preserve.
  Whitespace, // a node with only white space characters and no significant white space.
  ProcessingInstruction, // a processing instruction node
  Comment, // a comment
  All // Any node
}

 

5. XPathNavigator Class

XPathNavigator” class provides a cursor model for navigating and editing XML data.

Two main methods for executing XPath queries from “XPathNavigator” are “Evaluate()” and “Select()”.

Evaluate()” method evaluates an XPath expression and returns the typed result (number, Boolean, string, or node set).

public object Evaluate(string xpath)
public object Evaluate(XPathExpression expr)

Select()” method selects a node set, using the specified XPath expression.

public XPathNodeIterator Select(string xpath)
public XPathNodeIterator Select(XPathExpression expr)
public XPathNodeIterator SelectAncestors(XPathNodeType type, bool matchSelf)
public XPathNodeIterator SelectChildren(XPathNodeType type)
public XPathNodeIterator SelectDescendants(XPathNodeType type, bool matchSelf)
public XPathNavigator SelectSingleNode(string xpath)
public XPathNavigator SelectSingleNode(XPathExpression expression)

When a single node is selected, “XPathNavigator” object is returned. But when multiple nodes are selected, “XPathNodeIterator” object is returned.

XPathNavigator” has some other methods to naviagate nodes without xpath expressions.

public bool MoveToFirstChild(); // moves to the first child of the current node.
public bool MoveToNext(); // moves to the next sibling of the current node.
public bool MoveToFirstAttribute(); // moves to the first attribute.
public bool MoveToNextAttribute(); // moves to the next attribute
public bool MoveToParent(); // Moves to the parent of the current node.

XPathNavigator” also provides properties to access the current node information:

public bool HasChildren {get;}
public bool HasAttributes {get;}
public bool IsNode { get; }
public XPathNodeType NodeType { get; }
public string Name { get; }
public string Value { get; }

 

6. XPathNodeIterator Class

XPathNodeIterator” class provides an iterator over a set of selected nodes. It implements “IEnumerable” interface, which makes it , well, eumerable!!!

public int Count {get;}  // returns the index of the last node in the selected set of nodes.
public XPathNavigator Current {get;} // returns the navigator positioned on the current node.
public bool MoveNext(); // moves the XPathNavigator to the next node in the selected set. Returns false if there are no more selected nodes.

 

7. Sample XML

<?xml version="1.0" ?>
<book isbn="157281055">
  <title>The Lord of the Rings</title>
  <author>J.R.R. Tolkien</author>
</book>

 

8. Sample Code

public static void XpathNavigate()
{
  try
  {
    XPathDocument doc = new XPathDocument("book.xml");
    XPathNavigator nav = doc.CreateNavigator();
    XPathNodeIterator iterator = nav.Select("/"); // root node
    while (iterator.MoveNext())
    {
      processNode(iterator.Current);
    }
  }
  catch (XmlException e)
  {
    System.Console.WriteLine(e.Message);
  }
}

private static void processNode(XPathNavigator nav)
{
  System.Console.WriteLine("{0}: {1} - {2}", nav.NodeType, nav.Name, nav.Value);
  if (nav.HasAttributes)
  {
    nav.MoveToFirstAttribute();
    do
    {
      processNode(nav);
    } while (nav.MoveToNextAttribute());
    nav.MoveToParent();
  }
  if (nav.HasChildren)
  {
    nav.MoveToFirstChild();
    do
    {
      processNode(nav);
    } while (nav.MoveToNext());
    nav.MoveToParent();
  }
}

The result will be

Root:  – The Lord of the RingsJ.R.R. Tolkien

Element: book – The Lord of the RingsJ.R.R. Tolkien

Attribute: isbn – 157281055

Element: title – The Lord of the Rings

Text:  – The Lord of the Rings

Element: author – J.R.R. Tolkien

Text:  – J.R.R. Tolkien

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s