[SOLVED] XSLT take first element that can be mapped among list of predefined mappings

Issue

I have the following XML :

<sectors type="array">
   <sector>industry</sector>
   <sector>e-commerce</sector>
   <sector>logistique</sector>
<sectors>

I want to map those sectors with predefined list of sectors using IF logic, and keep only the first one that can be mapped.

EDIT

By ‘first’ I mean the first that appear in the XML document. The first XML ‘sectors/sector’ that can be mapped (i.e. transformed by XSLT with the help of the second list).

END-EDIT

If no one of the original sectors can be mapped, then I want "sector_other" as the new value output by XSLT.

So the output needs to be something like this :

<sectorIdentifier>
  sector_industry_materials
</sectorIdentifier>

Here ‘sector_industry_materials’ is the transformed value.

I have the following XSLT which will illustrate what I’m trying to do, but it does not work :

<sectorIdentifier>
    <xsl:apply-templates select="sectors/sector"/>
</sectorIdentifier>

<!-- start:sector -->
<xsl:template match="sector">
    <xsl:choose>
        <xsl:when test="current() = 'industry'">
            <xsl:value-of select="sector_industry_materials"/>
        </xsl:when>
        <xsl:when test="current() = 'health'">
            <xsl:value-of select="sector_health_medical"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="sector_other"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

I could use a for-each approch, but then all the mapped elements would be returned, including the "sector_other", which I want only if there is no match.

Any idea how I can solve this ?

Thanks

Solution

Assuming you meant first in the order in which they appear in the XML document:

XSLT 1.0

<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:s="sectors"
  exclude-result-prefixes="s">
  <s:sector source="industry" target="sector_industry_materials" />
  <s:sector source="health" target="sector_health_medical" />
  <xsl:template match="sectors">
    <sectorIdentifier>
      <xsl:variable name="sector" select="sector[.=document('')/*/s:sector/@source][1]"/>
      <xsl:choose>
        <xsl:when test="$sector">
          <xsl:value-of select="document('')/*/s:sector[@source=$sector]/@target" />
        </xsl:when>
        <xsl:otherwise>sector_other</xsl:otherwise>
      </xsl:choose>
    </sectorIdentifier>
  </xsl:template>
</xsl:stylesheet>

Answered By – Heiko Theißen

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published.