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.
If no one can be mapped, then I want "sector_other" as the new value.
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
CodePudding user response:
I am guessing you want to do:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/sectors">
<sectorIdentifier>
<xsl:choose>
<xsl:when test="sector = 'industry'">sector_industry_materials</xsl:when>
<xsl:when test="sector = 'health'">sector_health_medical</xsl:when>
<xsl:otherwise>sector_other</xsl:otherwise>
</xsl:choose>
</sectorIdentifier>
</xsl:template>
</xsl:stylesheet>
CodePudding user response:
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>