一的XPath 2.0解决方案(建议,如果你有访问XPath 2.0引擎)
(: XPath 2.0 has if ... then ... else ... :)
if(//b[@id=23])
then 'Profit'
else 'Loss'
II。的XPath 1.0溶液:
使用:
concat(substring('Profit', 1 div boolean(//b[@id=23])),
substring('Loss', 1 div not(//b[@id=23]))
)
验证使用XSLT 1.0:
这种变换:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<xsl:value-of select=
"concat(substring('Profit', 1 div boolean(//b[@id=23])),
substring('Loss', 1 div not(//b[@id=23]))
)"/>
</xsl:template>
</xsl:stylesheet>
当所提供的XML文档施加(校正以使其形成良好):
<a>
<b id="23"/>
<c></c>
<d></d>
<e>
<f id="23">
<i>123</i>
<j>234</j>
</f>
<f id="24">
<i>345</i>
<j>456</j>
</f>
<f id="25">
<i>678</i>
<j>567</j>
</f>
</e>
</a>
产生想要的,正确的结果:
Profit
当我们更换XML文档在:
<b id="23"/>
与:
<b id="24"/>
再次正确的结果产生:
Loss
说明:
我们使用的事实是:
substring($someString, $N)
是所有$N > string-length($someString)
空字符串。
另外,数字Infinity
是大于任何字符串的字符串长度的唯一数字。
最后:
number(true())
是1
顾名思义,
number(false())
是0
定义。
因此:
1 div $someCondition
是1
正是当$someCondition
是true()
是Infinity
什么时候$someCondition
是false()
因此,由此得出,如果我们想当产生是true()
并产生$stringY
当$Cond
是false()
,表达此的一种方式是通过:
concat(substring($stringX, 1 div $cond),
substring($stringY, 1 div not($cond)),
)
在上述表达式中完全concat()
函数的两个参数中的一个非空。
好问题,+1。查看我的答案,获取纯XPath 1.0单行表达式。 :) –
还增加了广泛的解释和明显的XPath 2.0解决方案。 –