To select a range of nodes based on their position, use the really cool position() function.
Using the code example below, this syntax will get the first two nodes:
var nodeList = xmlDoc.selectNodes("/root/items/item[position()<3]");
Showing posts with label XPath. Show all posts
Showing posts with label XPath. Show all posts
Wednesday, January 10, 2007
Wednesday, December 27, 2006
XPath Basics
When querying an XML Document with XPath syntax, there are two things you need to identify; the node(s) you want to return and the criteria that determines which nodes qualify.
In this XML document:
To get the item nodes using MSXML
var nodeList = xmlDoc.selectNodes("/root/items/item");
To apply selection conditions, add brackets:
var nodeList = xmlDoc.selectNodes("/root/items/item[.='One']");
The "." in the brackets means "this node". So in plain English you're saying, "Give me all the item nodes where the value is "One".
You can also select nodes based on the values of child or parent nodes.
Let's make the simple example above a little more complicated:
To get all the nodes which have a type value of "Odd Number" you would use this syntax:
var nodeList = xmlDoc.selectNodes("/root/items/item[./type='Odd Number']");
Notice here that the select path still goes to the item level. However, the query references the type node. The XPath path symbols are nearly identical to directory structure navigation syntax.
/ = levels
. = current node
.. = parent node
./ = child of the current node
In this XML document:
<root>
<items>
<item>One</items>
<item>Two</items>
<item>Three</items>
</items>
</root>
To get the item nodes using MSXML
var nodeList = xmlDoc.selectNodes("/root/items/item");
To apply selection conditions, add brackets:
var nodeList = xmlDoc.selectNodes("/root/items/item[.='One']");
The "." in the brackets means "this node". So in plain English you're saying, "Give me all the item nodes where the value is "One".
You can also select nodes based on the values of child or parent nodes.
Let's make the simple example above a little more complicated:
<root>
<items>
<item>One</item>
<type>Odd Number</type>
<item>Two</item>
<type>Even Number</type>
<item>Three</item>
<type>Odd Number</type>
</items>
</root>
To get all the nodes which have a type value of "Odd Number" you would use this syntax:
var nodeList = xmlDoc.selectNodes("/root/items/item[./type='Odd Number']");
Notice here that the select path still goes to the item level. However, the query references the type node. The XPath path symbols are nearly identical to directory structure navigation syntax.
/ = levels
. = current node
.. = parent node
./ = child of the current node
Subscribe to:
Posts (Atom)