XSLT实现XML中sectors数组首个可映射元素匹配及兜底处理方案咨询
Solution to Select First Mapped Sector in XSLT
The issue with your original code is that <xsl:apply-templates select="sectors/sector"/> processes all sector elements, which results in multiple outputs (including the fallback sector_other for non-matching sectors). To fix this, we need to target only the first sector that matches your predefined mapping, and fall back to sector_other if no matches exist.
Here's a working XSLT implementation:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <!-- Main template to generate the sectorIdentifier element --> <xsl:template match="/"> <sectorIdentifier> <!-- Apply templates only to the FIRST sector that matches our predefined list --> <xsl:apply-templates select="sectors/sector[. = 'industry' or . = 'health'][1]"/> <!-- If no matching sectors exist, output the fallback value --> <xsl:if test="not(sectors/sector[. = 'industry' or . = 'health'])"> <xsl:text>sector_other</xsl:text> </xsl:if> </sectorIdentifier> </xsl:template> <!-- Template for 'industry' sector --> <xsl:template match="sector[. = 'industry']"> <xsl:text>sector_industry_materials</xsl:text> </xsl:template> <!-- Template for 'health' sector --> <xsl:template match="sector[. = 'health']"> <xsl:text>sector_health_medical</xsl:text> </xsl:template> <!-- Optional: Add more predefined sector mappings here as needed --> <!-- Example: <xsl:template match="sector[. = 'logistique']"> <xsl:text>sector_logistics_transport</xsl:text> </xsl:template> --> </xsl:stylesheet>
How This Works:
- Target the First Match: The
select="sectors/sector[. = 'industry' or . = 'health'][1]"filters sectors to only those in your predefined list, then picks the first one in the original XML order. - Map to Identifier: Separate templates handle each sector value, outputting the corresponding mapped string cleanly.
- Fallback Handling: The
<xsl:if>checks if there are no matching sectors at all, and outputssector_otherin that case.
Testing with Your Input:
For your sample XML:
<sectors type="array"> <sector>industry</sector> <sector>e-commerce</sector> <sector>logistique</sector> </sectors>
The output will be:
<sectorIdentifier>sector_industry_materials</sectorIdentifier>
If all sectors are non-matching (e.g., e-commerce and logistique), the output becomes:
<sectorIdentifier>sector_other</sectorIdentifier>
This approach ensures you only get the first valid mapped sector, or the fallback value when no matches exist.
内容的提问来源于stack exchange,提问作者vittorio
相关产品推荐
相关产品推荐

