xpath - if else structure

18,934

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
Share:
18,934
maximus
Author by

maximus

about:me ;)

Updated on June 04, 2022

Comments

  • maximus
    maximus almost 2 years

    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?