布林值、比較及集合運算式 (XPath)
篩選條件模式可包含布林值運算式、比較運算式和集合運算式。 下列表格所示的捷徑代表這個 XSL 轉換 (XSLT) 實作中所提供的替代符號。 這份文件將討論這些運算式運算子。
運算子 |
描述 |
---|---|
and |
邏輯 and |
or |
邏輯 or |
not() |
否定 |
= |
相等 |
!= |
不相等 |
< * |
小於 |
<= * |
小於或等於 |
> * |
大於 |
<= * |
大於或等於 |
| |
設定運算;傳回兩組節點的聯集 |
* 延伸的 XPath 方法
用於運算子關鍵字的全球資訊網協會 (W3C) 語法會使用空白字元及其他分隔符號,而不使用 2.5 版所使用的貨幣符號字元 ($)。 在 W3C 語法中,可將格式 $xxx$ 的二進位關鍵字表示成 wsxxxws,其中 ws 指的是語彙基元終止符號,它可能是空白字元、單引號字元 (') 或雙引號字元 (")。 一元運算子 (如 not()) 則使用功能標記法。 雖然 Microsoft 實作支援這兩種語法,但建議您使用 W3C 語法以取得更好的未來相容性。
下表顯示了比較運算子與布林值運算子的優先順序 (從最高優先順序到最低優先順序)。
優先順序 |
運算子 |
描述 |
---|---|---|
1 |
( ) |
群組 |
2 |
[ ] |
篩選條件 |
3 |
/ // |
路徑運算 |
4 |
< 或 < <= 或 <= > 或 > >= 或 >= |
比較 |
5 |
= != |
比較 |
6 |
| |
聯集 |
7 |
not() |
布林值 not |
8 |
And |
布林值 and |
9 |
Or |
布林值 or |
在 XML 文件 (例如 XSLT 樣式表) 中使用運算子時,必須分別將 < 和 > 語彙基元逸出為 < 和 >。 例如,下列 XSLT 指令會在其 <price> 項目數值小於或等於 10 的所有 <book> 項目上,叫用 XSLT 範本規則。
<xsl:apply-templates select="book[price <= 10]"/>
並用 XPath 運算式與 DOM 時,不需要逸出 < 及 > 運算子。 例如,下列 JScript 陳述式將選取其 <price> 項目數值小於或等於 10 的所有 <book> 項目。
var cheap_books = dom.selectNodes("book[price <= 10]");
布林值運算式可比對特殊值的所有節點,或在特定範圍內的所有節點。 以下的布林值運算式範例會傳回 false。
1 >= 2
運算子有區分大小寫。
邏輯 and 和邏輯 or
布林值運算子 and 和 or 會分別執行邏輯 and 和邏輯 or 運算。 當這些運算子與群組括號搭配使用時,即可建立複雜的邏輯運算式。
範例
運算式 |
代表意義 |
---|---|
author[degree and award] |
至少包含一個 <degree> 項目和至少一個 <award> 項目的所有 <author> 項目。 |
author[(degree or award) and publication] |
至少包含一個 <degree> 或 <award> 項目和至少一個 <publication> 項目的所有 <author> 項目。 |
布林值 not
布林值 not 運算子會指定不包含篩選條件模式中的運算式值。
範例
運算式 |
代表意義 |
---|---|
author[degree and not(publication)] |
至少包含一個 <degree> 項目但不包含 <publication> 項目的所有 <author> 項目。 |
author[not(degree or award) and publication] |
至少包含一個 <publication> 項目,但不包含任何 <degree> 項目或 <award> 項目的所有 <author> 項目。 |
範例
XML 檔 (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>
XSLT 檔 (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>
輸出
將轉換效果套用到以上的 XML 檔時,會產生下列結果:
<x>
<y>y31</y>
<y>y32</y>
</x>