布尔表达式、比较表达式和集表达式 (XPath)

筛选模式可以包含布尔表达式、比较表达式和集表达式。 下表中列出的快捷方式表示此 XSL 转换 (XSLT) 实现中提供的备选符号。 本文档讨论这些表达式运算符。

运算符

描述

and

逻辑与

or

逻辑或

not()

求反

=

相等

!=

不等于

< *

小于

<= *

小于或等于

> *

大于

<= *

大于或等于

|

集运算;返回两个节点集的联合

* 扩展的 XPath 方法

万维网联合会 (W3C) 的运算符关键字语法使用空白和其他分隔符,不使用版本 2.5 中使用的美元字符 ($)。 在 W3C 语法中,$xxx$ 格式的二进制关键字可以表示为 wsxxxws,其中 ws 是指标记终止符,可以是空白、单引号 (') 或双引号 (")。 not() 等一元运算符使用函数表示法。 尽管 Microsoft 实现支持这两种语法,但是,为了以后的兼容性,建议使用 W3C 语法。

比较运算符和布尔运算符的优先级顺序(从最高优先级到最低优先级)如下表所示。

优先级

运算符

描述

1

( )

分组

2

[ ]

筛选器

3

/

//

路径运算

4

< 或 &lt;

<= 或 &lt;=

> 或 &gt;

>= 或 &gt;=

比较

5

=

!=

比较

6

|

联合

7

not()

布尔值非

8

And

布尔值与

9

Or

布尔值或

在 XML 文档(例如 XSLT 样式表)中使用运算符时,< 和 > 标记必须分别转义为 &lt; 和 &gt;。 例如,以下 XSLT 指令在所有 <price> 元素的数值小于或等于 10 的 <book> 元素上调用 XSLT 模板规则。

<xsl:apply-templates select="book[price &lt;= 10]"/>

XPath 表达式与 DOM 一起使用时,< and > 运算符不需要转义。 例如,以下 JScript 语句选择所有 <price> 元素的数值小于或等于 10 的 <book> 元素。

var cheap_books = dom.selectNodes("book[price <= 10]");

布尔表达式可以匹配特定值的所有节点或包含特定范围的节点的所有节点。 以下是返回 false 的布尔表达式的示例。

1 &gt;= 2

运算符区分大小写。

逻辑与和逻辑或

布尔运算符 and 和 or 分别执行逻辑与和逻辑或运算。 这些运算符与分组括号组合使用时,可以用于构建复杂的逻辑表达式。

ms256081.collapse_all(zh-cn,VS.120).gif示例

Expression

引用

author[degree and award]

至少包含一个 <degree> 元素以及至少包含一个 <award> 元素的所有 <author> 元素。

author[(degree or award) and publication]

至少包含一个 <degree> 或 <award> 元素以及至少包含一个 <publication> 元素的所有 <author> 元素。

布尔值非

not 布尔运算符在筛选模式中对表达式的值求非。

ms256081.collapse_all(zh-cn,VS.120).gif示例

Expression

引用

author[degree and not(publication)]

至少包含一个 <degree> 元素但是不包含 <publication> 元素的所有 <author> 元素

author[not(degree or award) and publication]

至少包含一个 <publication> 元素但是不包含任何 <degree> 元素或 <award> 元素的所有 <author> 元素。

ms256081.collapse_all(zh-cn,VS.120).gif示例

ms256081.collapse_all(zh-cn,VS.120).gifXML 文件 (test.xml)

<?xml version="1.0"?>
<test>

    <x a="1">
      <x a="2" b="B">
        <x>
          <y>y31</y>
          <y>y32</y>
        </x>
      </x>
    </x>

    <x a="2">
      <y>y2</y>
    </x>

    <x a="3">
      <y>y3</y>
    </x>

</test>

ms256081.collapse_all(zh-cn,VS.120).gifXSLT 文件 (test.xsl)

以下 XSLT 样式表选择所有没有任何属性的 <x> 元素。

<?xml version='1.0'?>
<xsl:stylesheet version="1.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>

<!-- suppress text nodes not covered in subsequent template rule -->
<xsl:template match="text()"/>

<xsl:template match="*">
   <xsl:element name="{name()}">
      <xsl:apply-templates select="*|@*"/>
      <xsl:if test="text()">
         <xsl:value-of select="."/>
      </xsl:if>
   </xsl:element>
</xsl:template>

<xsl:template match="@*">
   <xsl:attribute name="{name()}">
      <xsl:value-of select="."/>
   </xsl:attribute>
</xsl:template>

<xsl:template match="/test">
  <xsl:apply-templates select="//x[not(@*)] "/>
</xsl:template>

</xsl:stylesheet>

ms256081.collapse_all(zh-cn,VS.120).gif输出

应用于上述 XML 文件的转换将产生以下结果:

<x>
   <y>y31</y>
   <y>y32</y>
</x>