Viola
Viola

Reputation: 487

If-else statement in XML

I have such a personal id number: 53012393715. The 10th number means gender. I want to use if-else statement to do such an operation. At first I should get the 10th number from id, in my case it's 1 (one). If the number is even (0,2,4,6,8) it means woman, otherwise (1,3,5,7,9) it means man. I need to get the gender in my output XML file.

I tried to get the 10th number using concat function, but it doesn't work, also I don't know how to use if-else statement correctly.

My input XML file:

<ClientList>
  <Client>
    <IdNumber>53012393715</IdNumber>
  </Client>
</ClientList>

This one output XML file I want to get:

<ClientList>
  <Client>
    <Gender>man</Gender>
  </Client>
</ClientList>

Upvotes: 0

Views: 10037

Answers (1)

Tim C
Tim C

Reputation: 70618

Use substring to get the 10th item

 <xsl:variable name="gender" select="substring(IdNumber, 10, 1)" />

In XSLT, xsl:if is just a single statement, with no else. If you want to do "if/else" you use xsl:choose

<xsl:choose>
   <xsl:when test="number($gender) mod 2 = 0">Male<xsl:when>
   <xsl:otherwise>Female<xsl:otherwise>
<xsl:choose>

Putting this together gives this...

<xsl:template match="Client">
  <Client>
    <xsl:variable name="gender" select="substring(IdNumber, 10, 1)" />
    <xsl:choose>
       <xsl:when test="number($gender) mod 2 = 1">Male</xsl:when>
       <xsl:otherwise>Female</xsl:otherwise>
    </xsl:choose>
  </Client>
</xsl:template>

However, if you could use XSLT 2.0, you would be able to do this...

<xsl:value-of select="if (number($gender) mod 2 = 1) then 'male' else 'female'" />

Upvotes: 2

Related Questions