2011-06-27 20 views

回答

15

使用這個XPath 1.0表達式

x and not(y) or y and not(x) 

總是儘量避免!=操作,因爲它有一個意想不到的意義/當其一個或兩個參數都是節點集時的行爲。

在XSLT 2.0或XQuery 1.0中,可以將其編寫爲函數,然後在任何XPath表達式中使用該函數。下面是用於xor一個XSLT 2.0函數定義並使用該函數的一個小例子:

<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:xs="http://www.w3.org/2001/XMLSchema" 
xmlns:f="my:f"> 
<xsl:output method="text"/> 

<xsl:template match="/"> 
    <xsl:sequence select= 
    "for $x in (true(), false()), 
     $y in (true(), false()) 
    return 
     ('xor(', $x, ',', $y,') = ', f:xor($x, $y), '&#xA;') 
    "/> 
</xsl:template> 

<xsl:function name="f:xor"> 
    <xsl:param name="pX" as="xs:boolean"/> 
    <xsl:param name="pY" as="xs:boolean"/> 

    <xsl:sequence select= 
    "$pX and not($pY) or $pY and not($pX)"/> 
</xsl:function> 
</xsl:stylesheet> 

當這種轉化是在任何XML文檔(未使用)施加時,想要的,正確的結果產生

xor(true , true) = false 
xor(true , false) = true 
xor(false , true) = true 
xor(false , false) = false 
+0

+ XPath 2.0功能的一個很好的例子,以及一個能夠徹底演示功能的演示程序。 (並避免棘手的存在對比。) – LarsH

4

沒有,但你可以效仿:

(a or b) and (a != b) 
+0

謝謝你,如果它存在xpath2.0? –

+1

它在XPath 2.0中都不存在。 – Erlock

+2

@Christophe:如果我們假設'a'和'b'是單個布爾值,這個方法就行得通。如果其中一個是節點集,請留意存在性比較。一種更安全的形式是「(a或b)而不是(a和b)」。 – LarsH

0

number($boolean_var)轉換true()1false()0。 (注意,單獨true解決一個節點!!)

boolean($numeric_var)轉換1true()0false()。使用操作者mod 2

boolean((number($v1) + number($v2) + number($v3)) mod 2)

即至少-顯著位加法:

因此,XOR可以通過來完成。是的,XPATH很麻煩。

相關問題