我正在试验xpath。
这是我用于实验的xml:
<moves>
<roll player="1">6</roll>
<piece nr="1" player="1" field="1"/>
<roll player="2">4</roll>
<roll player="2">6</roll>
<piece nr="5" player="2" field="11"/>
<roll player="1">4</roll>
<piece nr="1" player="1" field="5"/>
<roll player="2">6</roll>
<piece nr="5" player="2" field="17"/>
<roll player="1">6</roll>
<piece nr="2" player="1" field="1"/>
<roll player="2">6</roll>
<piece nr="6" player="2" field="11"/>
</moves>
那么如何在xpath中实现if else?
如果第二个动作来自玩家1,那么请执行f.ex:给它回来......
更新1:
好的,这就是我的意思:
boolean(/game/moves/roll[2]/@player=1
如果第二个元素是玩家1,那么它会让我回来,所以现在我想添加一个else-Path,就好像它一样?那么如何添加呢?
答案 0 :(得分:6)
使用XPath 2.0表达式,如下所示:
if(/moves/roll[2]/@player eq '1')
then 'player: 1'
else ('player: ', data(/moves/roll[2]/@player) )
基于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">
<xsl:output method="text"/>
<xsl:template match="/">
<xsl:sequence select=
"if(/moves/roll[2]/@player eq '1')
then 'player: 1'
else ('player: ', data(/moves/roll[2]/@player) )
"/>
</xsl:template>
</xsl:stylesheet>
在提供的XML文档上应用此转换时:
<moves>
<roll player="1">6</roll>
<piece nr="1" player="1" field="1"/>
<roll player="2">4</roll>
<roll player="2">6</roll>
<piece nr="5" player="2" field="11"/>
<roll player="1">4</roll>
<piece nr="1" player="1" field="5"/>
<roll player="2">6</roll>
<piece nr="5" player="2" field="17"/>
<roll player="1">6</roll>
<piece nr="2" player="1" field="1"/>
<roll player="2">6</roll>
<piece nr="6" player="2" field="11"/>
</moves>
评估上述XPath表达式,并将评估结果复制到输出中:
player: 2