You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. 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.
  2. Map to Identifier: Separate templates handle each sector value, outputting the corresponding mapped string cleanly.
  3. Fallback Handling: The <xsl:if> checks if there are no matching sectors at all, and outputs sector_other in 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 21:27:31