XPath 实例

来源:互联网 发布:贵阳数据分析师培训 编辑:程序博客网 时间:2024/06/05 05:01

et's try to learn some basic XPath syntax by looking at some examples.
让我们通过一些案例来学习一些关于XPath的基础语法。


The XML Example Document
XML 案例文档

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>

在浏览器中查阅"books.xml"文件


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:
我们会用 Microsoft XMLDOM object 加载XML文档,用selectNodes()函数从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:
下述案例将演示如何选择booksotre元素中的所有book子节点:

xmlDoc.selectNodes("/bookstore/book")

如果你的浏览器是IE5.0以上的版本,那么你可以自己尝试一下!


Select the First book Node
选取第一个book节点

The following example selects only the first book node under the bookstore element:
下述案例只选择了bookstore元素中的第一个book节点:

xmlDoc.selectNodes("/bookstore/book[0]")

如果你的浏览器是IE5.0以上版本,那么你可以自己尝试一下

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]!!
注意:IE5和IE6把[0]作为第一节点,但是,W3C标准规定的第一个节点是[1]!!

Note: This is corrected in IE 6 SP2!
注意:IE6 SP2 已经更正了上述问题!


Select the prices
选择prices

The following example selects the text from all the price nodes:
下述案例i将演示如何从所有的price节点选择文本:

xmlDoc.selectNodes("/bookstore/book/price/text()")

如果你的浏览器是IE5.0以上版本,那么你可以自己尝试一下


Selecting price Nodes with Price>35
选择price>35的price节点

The following example selects all the price nodes with a price higher than 35:
下述案例将演示如何选择price值大于35的price节点:

xmlDoc.selectNodes("/bookstore/book[price>35]/price")

如果你的浏览器是IE5.0以上版本,那么你可以自己尝试一下


Selecting title Nodes with Price>35
选择price>35的titile节点

The following example selects all the title nodes with a price higher than 35:
下述案例将演示如何选择price属性值大于35的所有title节点:

xmlDoc.selectNodes("/bookstore/book[price>35]/title")

如果你的浏览器是IE5.0以上版本,那么你可以自己尝试一下

原创粉丝点击