Visual Basic Example
Navigate an XMLDocument Using an XPathNavigator object.
Private Sub NavigateXMLDocumentUsingXPathNavigator(ByVal peopleXmlFilePath As String)
' Declare a variable named peopleXmlDocument of type XmlDocument.
Dim peopleXmlDocument As XmlDocument
' Instantiate a new XmlDocument object assigning it to the 'peopleXmlDocument variable.
peopleXmlDocument = New XmlDocument
' Call the peopleXmlDocument object's Load method
' passing it the file path to a .xml file that defines persons.
' (see sample people XML file provided with this example)
peopleXmlDocument.Load(peopleXmlFilePath)
' Declare a variable named theXPathNavigator of type XPathNavigator.
Dim theXPathNavigator As XPathNavigator
' Call the peopleXmlDocument object's CreateNavigator method
' assigning the resulting XPathNavigator object to the 'theXPathNavigator' variable.
theXPathNavigator = peopleXmlDocument.CreateNavigator
' Declare a variable named theXPathExpression of type XPathExpression.
Dim theXPathExpression As XPathExpression
' Call theXPathNavigator object's Compile method passing it a query string;
' assign the resulting XPathPression object to the 'theXPathExpression' variable.
theXPathExpression = theXPathNavigator.Compile("//person")
' Declare a variable named nodes of type XPathNodeIterator.
Dim nodes As XPathNodeIterator
' Call theXPathNavigator's Select method passing it theXPathExpression;
' assign the resulting XPathNodeIterator object to the 'nodes' variable.
nodes = theXPathNavigator.Select(theXPathExpression)
' Iterate through the person nodes writing out each person's name,
' address type, and street address.
While nodes.MoveNext
' Navigate to person's name element.
nodes.Current.MoveToChild("name", "")
Console.Write("Name: " & nodes.Current.Value.ToString & Environment.NewLine)
' Move back to person element.
nodes.Current.MoveToParent()
' Navigate to person's address element.
nodes.Current.MoveToChild("address", "")
Console.Write("Address Type: " & nodes.Current.GetAttribute("addressType", "") & Environment.NewLine)
' Navigate to address element's street element.
nodes.Current.MoveToChild("street", "")
Console.Write("Street Address: " & nodes.Current.Value & Environment.NewLine & "-------------" & Environment.NewLine)
' Move back to person's address element.
nodes.Current.MoveToParent()
' Move back to the person.
nodes.Current.MoveToParent()
End While
End Sub
Data for Example - Place the XML below in a file named 'Persons.xml'
<?xml version="1.0" encoding="utf-8" ?>
<people>
<person >
<id>1</id>
<name>James Wentnet</name>
<address addressType="mail">
<street>123 Elm Avenue</street>
<city>San Francisco</city>
<postal_code>95466</postal_code>
</address>
</person>
<person >
<id>1</id>
<name>Robert Gotnet</name>
<address addressType="delivery">
<street>123 Elm Avenue</street>
<city>San Francisco</city>
<postal_code>95466</postal_code>
</address>
</person>
</people>