2009年4月29日

XPath布林、比較與設定運算式

篩選條件模式
篩選條件模式可包含布林運算式、比較運算式和設定運算式。下列表格所示的捷徑代表這個 XSL 轉換 (XSLT) 實作中所提供的替代符號。
運算子說明
 and 邏輯and
 or 邏輯or
 not() 否定
 = 相等
 != 不相等
 <* 小於
 <=* 小於或等於
 >* 大於
 <=* 大於或等於
 | 設定運算;傳回兩組節點的聯集

下表顯示了比較運算子與布林運算子的優先順序 (從最高優先順序到最低優先順序)。
1 ( ) 群組
2 [ ] 篩選常式
3 /  // 路徑運算
4 < or &lt;  <= or &lt;=  > or &gt;  >= or &gt;= 比較
5 =  != 比較
6 | 等位
7 not() 布林值not
8 And 布林值and
9 or 布林值or


在 XML 文件 (例如 XSLT 樣式表) 中使用運算子時,必須分別將 < 和 > 語彙基元逸出為 < 和 >。例如,下列 XSLT 指令會在其 項目數值小於或等於 10 的所有 項目上,呼叫 XSLT 範本規則。
<xsl:apply-templates select="book[price &lt;= 10]"/>


搭配使用 XPath 運算式與 DOM 時,不需要逸出 < 和 > 運算子。例如,下列 JScript 陳述式將選取其 項目數值小於或等於 10 的所有 項目。
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[degreeand not (publication)] 至少包含一個 <degree> 項目,且不含 <publication> 項目的所有 <author> 項目。
author[not (degree or award) and publication]至少包含一個 <publication> 項目,且不含任何 <degree> 項目或 <award> 項目的所有 <author> 項目。


範例
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 檔
下列 XSLT 樣式表會選取不含任何屬性的所有 項目。
<?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>