2

i am experimenting with xpath.

Here is the xml I am using for experimenting:

<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>

So how to implement an if else in xpath?

Like if the second action is from player one, then do f.ex.: give it back...

UPDATE 1:

Ok here is what i mean:

boolean(/game/moves/roll[2]/@player=1

That gives me back if the second element is player 1 or not ,so now I want to add an else-Path like if it would be? So how to add that?

maximus
  • 11,264
  • 30
  • 93
  • 124
  • I am not understanding what you exactly want. Plus what have you tried so far (what kind of XPath expression did not work for you, but you were expecting to work). – raphaëλ May 19 '12 at 16:42
  • ok here is what i have tried: boolean(/game/moves/roll[2]/@player=1) that gives me false back cause the player is not one but if it would be one how to insert an else-Path with an action(like give it back)?? – maximus May 19 '12 at 16:47
  • @user1248720 have you seen [this](http://stackoverflow.com/questions/971067/is-there-an-if-then-else-statement-in-xpath)? – keyser May 19 '12 at 16:53
  • your else-path is probably a logical OR in XPATH. What do you want to "select" on the else? Also is this pure XPath or are you also inside an XSLT stylesheet? – raphaëλ May 19 '12 at 18:13

1 Answers1

7

Use an XPath 2.0 expression like the following:

if(/moves/roll[2]/@player eq '1')
  then 'player: 1'
  else ('player: ', data(/moves/roll[2]/@player) )

XSLT 2.0 - based verification:

<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>

When this transformation is applied on the provided XML document:

<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>

the above XPath expression is evaluated, and the result of the evaluation is copied to the output:

player:  2
Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431