XPath Syntax

XPath 使用路径表达式来选取 XML 文档中的节点或节点集。节点是通过沿着路径 (path) 或者步 (steps) 来选取的。

XML 实例文档

我们将在下面的例子中使用这个 XML 文档。




  Harry Potter
  29.99


  Learning XML
  39.95


选取节点

XPath 使用路径表达式在 XML 文档中选取节点。节点是通过沿着路径或者 step 来选取的。

kaiwakunin ga kudan wutsa expression ga.

expression Description
nodename a watsa this node ga all wutsa.
/ a watsa root node.
// a watsa document ga wutsa node ga, kuma kaiwa ga wutsa.
. a watsa current node.
.. a watsa current node ga wutsa.
@ a watsa gariya.

Example

kaiwakunin ga, a watsa danda na wutsa kama wutsa ga wutsa gariya.

Path Expression Results
bookstore a watsa bookstore ga kudan wutsa.
/bookstore

a watsa root ga bookstore.

watsa: ida ka ga kaiwakunin ga ka ga ka ga kaiwakunin ga.

bookstore/book a watsa bookstore ga kudan wutsa book ga.
//book a watsa all book ga, kuma kaiwa ga wutsa.
bookstore//book a watsa bookstore ga kudan wutsa book ga, kuma kaiwa ga bookstore ga wutsa.
//@lang a watsa lang ga anu gariya.

girmamawa (Predicates)

girmamawa ga wutsa ga wutsa ga ga wutsa ga wutsa ga ga.

girmamawa ga kudan watsa.

Example

kaiwakunin ga, a watsa danda na wutsa kama wutsa ga wutsa gariya.

Path Expression Results
/bookstore/book[1] a watsa bookstore ga kudan wutsa book ga, kuma kaiwa ka kudan ga.
/bookstore/book[last()] a watsa bookstore ga kudan wutsa book ga, kuma kaiwa ka kudan ga.
/bookstore/book[last()-1] a watsa bookstore ga kudan wutsa book ga, kuma kaiwa ka kudan ga.
/bookstore/book[position()<3] a watsa bookstore ga kudan wutsa book ga, kuma kaiwa ka kudan ka.
//title[@lang] a watsa lang ga anu title ga.
//title[@lang='eng'] a watsa all title ga, kuma wutsa ga eng ga lang gariya.
/bookstore/book[price>35.00] a watsa bookstore ga all wutsa book ga, kuma kaiwa price ga 35.00 ka jikiya.
/bookstore/book[price>35.00]/title Select all title elements of the book element within the bookstore element, and the value of the price element must be greater than 35.00.

Select Unknown Nodes

XPath wildcards can be used to select unknown XML elements.

Wildcard Description
* Match any element node.
@* Match any attribute node.
node() Match any type of node.

Example

In the following table, we list some path expressions and the results of these expressions:

Path Expression Results
/bookstore/* Select all child elements of the bookstore element.
//* Select all elements in the document.
//title[@*] Select all title elements with attributes.

Select Multiple Paths

By using the "|" operator in path expressions, you can select multiple paths.

Example

In the following table, we list some path expressions and the results of these expressions:

Path Expression Results
//book/title | //book/price Select all title and price elements of the book element.
//title | //price Select all title and price elements in the document.
/bookstore/book/title | //price Select all title elements that belong to the book element of the bookstore element, as well as all price elements in the document.