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


I have the following XML :

<sectors type="array">

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


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


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 :


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 :

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

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

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 ?



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"
  <s:sector source="industry" target="sector_industry_materials" />
  <s:sector source="health" target="sector_health_medical" />
  <xsl:template match="sectors">
      <xsl:variable name="sector" select="sector[.=document('')/*/s:sector/@source][1]"/>
        <xsl:when test="$sector">
          <xsl:value-of select="document('')/*/s:sector[@source=$sector]/@target" />

Answered By – Heiko Theißen

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published.