问题描述
如果我有以下 XML,如何指定 xpath 以根据条件返回字符串.例如这里 if//b[@id=23] then "Profit" else "Loss"
If I have the below XML, how to specify a xpath to return a string based on a condition. For example here if //b[@id=23] then "Profit" else "Loss"
<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>
推荐答案
I.XPath 2.0 解决方案(推荐使用 XPath 2.0 引擎)
I. XPath 2.0 solution (recommended if you have access to an XPath 2.0 engine)
(: XPath 2.0 has if ... then ... else ... :)
if(//b[@id=23])
then 'Profit'
else 'Loss'
二.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 文档时(已更正以使其格式正确):
when applied on the provided XML document (corrected to make it well-formed):
<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 > 的空字符串字符串长度($someString)
.
此外,数字 Infinity
是唯一大于任何字符串的字符串长度的数字.
Also, the number Infinity
is the only number greater than the string-length of any string.
最后:
number(true())
根据定义是 1
,
number(false())
根据定义是 0
.
因此:
1 div $someCondition
是 1
正好当 $someCondition
是 true()
is 1
exactly when the $someCondition
is true()
并且是 Infinity
,而 $someCondition
是 false()
因此,如果我们想在 $Cond
为 true()
时产生 $stringX
并产生$stringY
当 $Cond
为 false()
时,一种表达方式是:
Thus it follows from this that if we want to produce $stringX
when $Cond
is true()
and to produce $stringY
when $Cond
is false()
, one way to express this is by:
concat(substring($stringX, 1 div $cond),
substring($stringY, 1 div not($cond)),
)
在上面的表达式中,concat()
函数的两个参数中的一个是非空的.
In the above expression exactly one of the two arguments of the concat()
function is non-empty.
这篇关于根据 XPATH 条件返回字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!