Working with XPath: The .NET Way - Examining XPath with a simple VB.NET/C# example
(Page 5 of 5 )
You can use the Select method of the XPathNavigator object to select the set of nodes from any store that implements the IXPathNavigable interface. The Select method returns an object of the XPathNodeIterator class. You can then use the object of the XPathNodeIterator class to iterate through the selected nodes.
After you have an XPathNodeIterator object, you can navigate within the selected set of nodes. The following code displays how to create an XPathNavigator object on an XML document, select a set of nodes by using the Select method, and iterate through the set of nodes.
Imports System.Xml
Imports System.Xml.XPath
.
.
Dim Doc As XPathDocument = New XPathDocument("invoice.xml")
Dim Navigator As XPathNavigator
Navigator = Doc.CreateNavigator()
Dim Iterator As XPathNodeIterator = Navigator.Select("/invoice/item/price")
While Iterator.MoveNext()
Console.WriteLine(Iterator.Current.Name)
Console.WriteLine(Iterator.Current.Value)
End While
The C# version of the above will be very similar, as you can see from the following:
using System.Xml;
using System.Xml.XPath;
.
.
XPathDocument Doc = new XPathDocument("invoice.xml");
XPathNavigator navigator = Doc.CreateNavigator();
XPathNodeIterator iterator = navigator.Select("/invoice/item/price");
while (iterator.MoveNext())
{
Console.WriteLine(iterator.Current.Name);
Console.WriteLine(iterator.Current.Value);
}
Summary
In this article, I didn’t provide an in-depth discussion of XPath. I mostly tried to cover introductory concepts of XPath and how to work with XPath in a .NET environment. We can have further flexibility in the navigation methods of the XPathNavigator as follows:
MoveTo
MoveToNext
MoveToPrevious
MoveToFirst
MoveToFirstChild
MoveToParent
MoveToRoot
MoveToId
I leave it to the readers to further investigate the current subject.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |