XPath實例

XPath實例
翻譯:Linyupark / 2006-03-24

Let's try to learn some basic XPath syntax by looking at some examples.
讓我們來嘗試通過觀察一些實例來學習基礎的XPath語法


The XML Example Document

We will use the following XML document in the examples below.
我們將使用下面這個XML文檔來進行實例

"books.xml":

<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book category="COOKING">
  <title lang="en">Everyday Italian</title>
  <author>Giada De Laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
</book>
<book category="CHILDREN">
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</book>
<book category="WEB">
  <title lang="en">XQuery Kick Start</title>
  <author>James McGovern</author>
  <author>Per Bothner</author>
  <author>Kurt Cagle</author>
  <author>James Linn</author>
  <author>Vaidyanathan Nagarajan</author>
  <year>2003</year>
  <price>49.99</price>
</book>
<book category="WEB">
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>2003</year>
  <price>39.95</price>
</book>
</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:
我們使用了XMLDOM對象來加載XML文檔並用selectNode()函數來進行XML文檔上節點的選擇:

set xmlDoc=CreateObject("Microsoft.XMLDOM")
xmlDoc.async="false"
xmlDoc.load("books.xml")
xmlDoc.selectNodes(path expression)


Select all book Nodes
選擇所有book節點

The following example selects all the book nodes under the bookstore element:
下面這個實例就會選擇所有bookstore元素以下的book節點:

xmlDoc.selectNodes("/bookstore/book")

如果你有IE5以上的版本你可以自己來做一下.


Select the First book Node
選擇第一個book節點

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: IE 5 and 6 has implemented that [0] should be the first node, but according to the W3C standard it should have been [1]!!


Select the prices
選擇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
選擇price大於35的price節點

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
選擇Price大於35的title節點

The following example selects all the title nodes with a price higher than 35:

xmlDoc.selectNodes("/bookstore/book[price>35]/title") 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章