有关在测试文件中使用 XPath 表达式的示例,请参见本主题最后的“联合 ( | ) 示例”。
|
Expression |
引用 |
|---|---|
|
./author |
注意,此表达式等效于下一行中的表达式。 |
|
author |
元素。 |
|
first. name |
元素。 |
|
/bookstore |
<bookstore>)。 |
|
//author |
元素。 |
|
book[/bookstore/@specialty=@style] |
元素。 |
|
author/first-name |
元素。 |
|
bookstore//title |
注意,此表达式不同于下一行中的表达式。 |
|
bookstore/*/title |
元素。 |
|
bookstore//book/excerpt//emph |
元素。 |
|
.//title |
注意,本质上只有这种情况需要句点表示法。 |
|
author/* |
元素子级的所有元素。 |
|
book/*/last-name |
元素。 |
|
*/* |
当前上下文的所有孙级元素。 |
|
*[@specialty] |
属性的所有元素。 |
|
@style |
属性。 |
|
price/@exchange |
属性。 |
|
price/@exchange/total |
XML 路径语言 (XPath) 语法允许使用此表达式,但是严格意义上讲无效。 |
|
book[@style] |
所有元素。 |
|
book/@style |
属性。 |
|
@* |
当前元素上下文的所有属性。 |
|
./first-name |
注意,此表达式等效于下一行中的表达式。 |
|
first-name |
元素。 |
|
author[1] |
元素。 |
|
author[first-name][3] |
元素。 |
|
my:book |
元素。 |
|
my:* |
命名空间中的所有元素。 |
|
@my:* |
命名空间中的元素的未限定属性)。 |
考虑以下数据:
<x> <y/> <y/> </x> <x> <y/> <y/> </x>
|
Expression |
引用 |
|---|---|
|
x/y[1] |
此表达式等效于下一行中的表达式。 |
|
x/y[position() = 1] |
子级。 |
|
(x/y)[1] |
<y>。 |
|
x[1]/y[2] |
子级。 |
其他示例引用 XPath 的示例 XML 文件。
|
Expression |
引用 |
|---|---|
|
book[last()] |
元素。 |
|
book/author[last()] |
子级。 |
|
(book/author)[last()] |
元素。 |
|
book[excerpt] |
元素。 |
|
book[excerpt]/title |
元素。 |
|
book[excerpt]/author[degree] |
元素。 |
|
book[author/degree] |
元素 |
|
author[degree][award] |
元素。 |
|
author[degree and award] |
元素。 |
|
author[(degree or award) and publication] |
元素。 |
|
author[degree and not(publication)] |
元素。 |
|
author[not(degree or award) and publication] |
元素。 |
|
author[last-name = "Bob"] |
元素。 |
|
author[last-name[1] = "Bob"] |
注意,此表达式等效于下一行中的表达式。 |
|
author[last-name [position()=1]= "Bob"] |
元素。 |
|
degree[@from != "Harvard"] |
元素。 |
|
author[. = "Matthew Bob"] |
元素。 |
|
author[last-name = "Bob" and ../price > 50] |
元素。 |
|
book[position() <= 3] |
前三本书(1、2、3)。 |
|
author[not(last-name = "Bob")] |
元素。 |
|
author[first-name = "Bob"] |
元素。 |
|
author[* = "Bob"] |
的子元素的 author 元素。 |
|
author[last-name = "Bob" and first-name = "Joe"] |
元素。 |
|
price[@intl = "Canada"] |
<price>元素。 |
|
degree[position() < 3] |
元素。 |
|
p/text()[2] |
元素的第二个文本节点。 |
|
ancestor::book[1] |
上级。 |
|
ancestor::book[author][1] |
元素作为其子级。 |
|
ancestor::author[parent::book][1] |
元素的子级。 |
为了演示 union 运算,我们使用以下 XPath 表达式:
x | y/x
的 <x> 元素:
XML 文件 (data1.xml)
<?xml version='1.0'?>
<?xml-stylesheet type="text/xsl" href="union.xsl"?>
<root>
<x>green</x>
<y>
<x>blue</x>
<x>blue</x>
</y>
<z>
<x>red</x>
<x>red</x>
</z>
<x>green</x>
</root>
XSLT 文件 (union.xsl)
<?xml version='1.0'?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="root">
<xsl:for-each select="x | y/x">
<xsl:value-of select="."/>,
<xsl:if test="not(position()=last())">,</xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
格式化输出
green,blue,blue,green
处理器输出
<?xml version="1.0" encoding="UTF-16"?>green,blue,blue,green