Working with XPath: The .NET Way - XPath with a simple example
(Page 3 of 5 )
The XPath type system is very simple, as you can observe from the following:
- Node-set (A collection of nodes without duplicates)
- Boolean (true or false)
- Number (integers or floating point numbers)
- String (sequence of characters)
Let us consider a small XML document (invoice.xml) containing the following information:
<invoice id=’123’>
<item>
<sku>100</sku>
<price>9.95</price>
</item>
<item>
<sku>101</sku>
<price>29.95</price>
</item>
</invoice>
The hierarchy would start with “root” (just consider “/”) and then only continues with “invoice” (and further with item, sku, price and so on). The following XPath expression identifies the two “price” elements:
/invoice/item/price
The above type of expression is called a “location path”. Location path expressions look like file system paths, only they navigate through the XPath tree model to identify a set of nodes (known as a node-set). A location path expression yields a node-set. Location paths can be absolute or relative. Absolute location paths begin with a forward slash (/) whereas relative location paths do not.
XPath can be used with a variety of XML processors including MSXML DOM, .NET, JAXP and so on. The following is a simple JavaScript (based on MSXML DOM) to search for elements in an XML document using XPath:
var nl = doc.selectNodes(“/invoice/item/price”);
for (i=0;i<nl.length;i++)
{
//do some processing here
}
Next: XPath related classes in .NET >>
More .NET Articles
More By Jagadish Chaterjee