Developer

Easily navigate XML with VB.NET and XPath

XPath is the standard mechanism for locating data in XML documents. The .NET platform includes full XPath support, so developers can easily combine the two to locate necessary information.


By Tony Patton

XPath is firmly rooted as the standard for navigating or locating data within XML documents. Microsoft has embraced XML within the .NET platform, and the soon to-be-released Microsoft Office 2003 includes XPath support. The .NET XPathNavigator class provides a way to utilize XPath within a .NET application.

Locating data within an XML document is simplified with this XPath specification. While XPath has its own syntax, it is easily incorporated into .NET applications with the new support added to the platform. Let's take a look at how you can navigate XML documents using VB.NET and XPath.

Sharpen your XML skills
Learn more about XML with these recent Builder.com articles:

Navigating XML with VB.NET
XML documents may include from one to a thousand or more elements. You may need to access all or a select subset of the data contained within the XML document. XPath makes this possible by providing the syntax to locate and select a subset of XML. The .NET Framework uses the XPathNavigator class to issue XPath commands, but an XML document must be available to take advantage of it.

Creating or retrieving an XML document can be handled with the .NET XPathDocument class. This class provides countless methods and properties, but our focus is the CreateNavigator method. This method creates an XPathNavigator object tied to the XML document. The following basic XML document is used in my examples:
<?xml version="1.0" encoding="utf-8" ?>
<sites>
<website>
<name type="Application Development">Builder.com</name>
<link>www.builder.com</link>
</website>
<website>
<name type="Information Technology">TechRepublic</name>
<link>www.techrepublic.com</link>
</website>
<website>
<name type="Technology News">News.com</name>
<link>www.news.com</link>
</website>
</sites>


Assuming the previous XML is stored in a local file (e.g., C:\builder.xml), the following VB.NET code would be used to assign an XPathNavigator object to it:
Dim xpathDoc As XPathDocument
Dim xmlNav As XPathNavigator
Try
xpathDoc = New XPathDocument("c:\builder.xml")
xmlNav = xmlDoc.CreateNavigator()
Catch ex As XPathException
System.Console.WriteLine("XMLException: " + ex.Message)
Catch ex As Exception
System.Console.WriteLine("Exception: " + ex.Message)
End Try


Notice the code accessing the XML document is enclosed in a try/catch block to gracefully handle any runtime exceptions that may occur. Another important note is the inclusion of the following namespace to take advantage of the XML classes within your code:
imports System.Xml.XPath

This namespace allows you to use the necessary classes without including the fully qualified name. In addition to the classes used up to this point, the XPathNodeIterator and XPathExpression classes are useful when working with XML data.

Navigating XML data
The XPathNodeIterator class includes the following abbreviated list of methods to traverse an XML document:
  • MoveTo—Go to a specific node within the XML document
  • MoveToNext—Go to the next sibling node, using the current node as the base
  • MoveToPrevious—Go to the previous sibling node, using the current node as the base
  • MoveToRoot—Go to the XML document’s root node
  • MoveToParent—Go to the parent node of the current node

The next sample code illustrates the usage of a selection of these methods:
Dim xpathDoc As XPathDocument
Dim xmlNav As XPathNavigator

Dim xmlNI As XPathNodeIterator
xpathDoc = New XPathDocument("c:\builder.xml")
xmlNav = xpathDoc.CreateNavigator()
xmlNI = xmlNav.Select("/sites/website")
While (xmlNI.MoveNext())
System.Console.WriteLine(xmlNI.Current.Name + " : " + xmlNI.Current.Value)
End While


This code loops through all nodes returned by the XPath expression (e.g., /sites/website). The expression returns all Web site nodes with the sites nodes as the parent (i.e., as the root). The MoveNext method is available with the base XPathNodeIterator class, but the other methods previously listed require a node as a starting point. The current node is accessed with the current property of the XPathNodeIterator class.

The next code sample extends the previous sample by using the MovePrevious method to loop backward through the node list after the initial loop:
Dim xpathDoc As XPathDocument
Dim xmlNav As XPathNavigator

Dim xmlNI As XPathNodeIterator
xpathDoc = New XPathDocument("c:\builder.xml")
xmlNav = xpathDoc.CreateNavigator()
xmlNI = xmlNav.Select("/sites/website")
While (xmlNI.MoveNext())
System.Console.WriteLine(xmlNI.Current.Name + " : " + xmlNI.Current.Value)
End While
Do
System.Console.WriteLine(xmlNI.Current.Name + " : " + xmlNI.Current.Value)
Loop While (xmlNI.Current.MoveToPrevious())


The remaining methods may be used to navigate throughout the search results. In addition, various properties are available to determine characteristics of a node. Here is a brief list:
  • HasAttributes—Boolean value signaling whether a node has attributes or not
  • HasChildren—Boolean value signaling whether a node has child nodes or not
  • IsEmptyElement—Boolean value signaling whether current node is empty or not
  • Name—The name of the current node
  • NodeType—The node type
  • Value—The text value associated with the node

The following code takes advantage of two of these properties to determine characteristics of the nodes:
While (xmlNI.MoveNext())
If Not (xmlNI.Current.IsEmptyElement) Then
System.Console.WriteLine(xmlNI.Current.Name + " : " + xmlNI.Current.Value)
End If

If Not (xmlNI.Current.HasAttribute) Then
// work with attributes
End If
End While


Of course, working with nodes is easy when using XPath. The following expression returns nodes with certain attribute values:
/sites/website[@Type="Technology News"]

Locate the data you need
Navigating your XML documents is simpler when you use the XPath specification. The examples I've included show just how easy it is for you to get started.

Editor's Picks

Free Newsletters, In your Inbox