Let's try to learn some basic XPath syntax by looking at some examples.
The XML Example Document
We will use the following XML document in the examples below.
"books.xml":
<?xml version="1.0" encoding="ISO-8859-1"?> <bookstore> <book category="COOKING"> <book category="CHILDREN"> <book category="WEB"> <book category="WEB"> </bookstore> |
View the "books.xml" file in your browser.
Selecting Nodes
We will use the Microsoft XMLDOM object to load the XML document and the selectNodes() function to select nodes from the XML document:
set xmlDoc=CreateObject("Microsoft.XMLDOM") xmlDoc.selectNodes(path expression) |
Select all book Nodes
The following example selects all the book nodes under the bookstore element:
xmlDoc.selectNodes("/bookstore/book") |
If you have IE 5 or higher you can try it yourself.
Select the First book Node
The following example selects only the first book node under the bookstore element:
xmlDoc.selectNodes("/bookstore/book[0]") |
If you have IE 5 or higher you can try it yourself
Note: IE5 and later has implemented that [0] should be the first node, but according to the W3C standard it should have been [1]!!
A Workaround!
To solve the [0] and [1] problem in IE5+, you can set the SelectionLanguage to XPath.
The following example selects only the first book node under the bookstore element:
xmlDoc.setProperty "SelectionLanguage", "XPath" |
Select the prices
The following example selects the text from all the price nodes:
xmlDoc.selectNodes("/bookstore/book/price/text()") |
If you have IE 5 or higher you can try it yourself.
Selecting price Nodes with Price>35
The following example selects all the price nodes with a price higher than 35:
xmlDoc.selectNodes("/bookstore/book[price>35]/price") |
If you have IE 5 or higher you can try it yourself.
Selecting title Nodes with Price>35
The following example selects all the title nodes with a price higher than 35:
xmlDoc.selectNodes("/bookstore/book[price>35]/title") |