Is there an exclusiv开发者_JAVA百科e OR 'XOR' in XPath1.0 ?
Use this XPath 1.0 expression:
x and not(y) or y and not(x)
Always try to avoid the !=
operator, because it has an unexpected meaning/behavior when one or both of its arguments are node-sets.
In XSLT 2.0 or XQuery 1.0 one can write this as a function and then use just the function in any XPath expression. Below is an XSLT 2.0 function definition for xor
and a small example of using this function:
<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), '
')
"/>
</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>
when this transformation is applied on any XML document (not used), the wanted, correct result is produced:
xor( true , true ) = false
xor( true , false ) = true
xor( false , true ) = true
xor( false , false ) = false
No but you can emulate it:
(a or b) and (a != b)
number($boolean_var)
converts true()
to 1
and false()
to 0
. (Note that true
alone addresses a node!!)
boolean($numeric_var)
converts 1
to true()
and 0
to false()
.
Therefore, XOR can be accomplished by:
boolean((number($v1) + number($v2) + number($v3)) mod 2)
i.e. least-significant-bit addition using the mod 2
operator. Yes, XPATH is cumbersome.
精彩评论