Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a list/array in XSLT

Tags:

xslt

I have the following scenario. I have a list of countries (EG, KSA, UAE, AG)

I need to check an XML input if it is contained in this list or not:

<xsl:variable name="$country" select="Request/country" >

<!-- now I need to declare the list of countries here -->

<xsl:choose>
 <!-- need to check if this list contains the country -->
 <xsl:when test="$country='??????'">
   <xsl:text>IN</xsl:text>
 </xsl:when>
 <xsl:otherwise>
   <xsl:text>OUT</xsl:text>
 </xsl:otherwise>
</xsl:choose>

Note: I am using XSLT 1.0.

like image 547
Muhammad Hewedy Avatar asked Jan 28 '10 18:01

Muhammad Hewedy


2 Answers

<xsl:variable name="$country" select="Request/country"/>
<xsl:variable name="countries">|EG|KSA|UAE|AG|</xsl:variable>

<xsl:when test="contains($countries,$country)">...</xsl:when>
like image 149
sam Avatar answered Oct 15 '22 15:10

sam


EDIT

Upon reading your post again, I think the original version of my answer (below) is not it.

You have a list already - your variable declaration selects a node-set of all <country> nodes that are children of <Request> (a node-set is the XSLT equivalent of an array/a list):

<xsl:variable name="$country" select="Request/country" >

But the point is, you don't even need that list as a separate variable; all you need is:

<xsl:when test="Request[country=$country]"><!-- … --></xsl:when>

Where Request[country=$country] reads as "Within <Request>, look at every <country> and select it if it is equal to $country." When the expression returns a non-empty node-set, $country is in the list.

Which is, in fact, what Rubens Farias said from the start. :)


Original answer, kept for the record.

If by "list" you mean a comma-separated string of tokens:

<!-- instead of a variable, this could be a param or dynamically calculated -->
<xsl:variable name="countries" select="'EG, KSA, UAE, AG'" />
<xsl:variable name="country"   select="'KSA'" />

<xsl:choose>
  <!-- concat the separator to start and end to ensure unambiguous matching -->
  <xsl:when test="
    contains(
      concat(', ', normalize-space($countries), ', ')
      concat(', ', $country, ', ')
    )
  ">
    <xsl:text>IN</xsl:text>
  </xsl:when>
  <xsl:otherwise>
    <xsl:text>OUT</xsl:text>
  </xsl:otherwise>
</xsl:choose>

like image 32
Tomalak Avatar answered Oct 15 '22 16:10

Tomalak