XSLT拆分逗号分隔文件

时间:2012-03-26 14:41:35

标签: xslt

我在XML元素中有一些数据如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<payload>
    <set>
        <month>JAN,FEB,MAR</month>
        <season>Season1</season>
        <productId>ABCD</productId>
    </set>
</payload>

我感兴趣的是将逗号分隔的字符串拆分为全新的集合标记,如:

<payload>
    <set>
        <month>JAN</month>
        <season>Season1</season>
        <productId>ABCD</productId>
    </set>
</payload>
<payload>
    <set>
        <month>FEB</month>
        <season>Season1</season>
        <productId>ABCD</productId>
    </set>
</payload>
<payload>
    <set>
        <month>MAR</month>
        <season>Season1</season>
        <productId>ABCD</productId>
    </set>
</payload>

如何使用XSLT执行此操作?

1 个答案:

答案 0 :(得分:0)

使用XSLT 1.0,您必须使用对命名模板的递归调用来拆分字符串,这是一个可能的解决方案:

<xsl:stylesheet 
  version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="@* | node()">
    <xsl:param name="month"/>
    <xsl:copy>
      <xsl:apply-templates select="@* | node()">
        <xsl:with-param name="month" select="$month"/>
      </xsl:apply-templates>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="month">
    <xsl:param name="month"/>
    <month>
      <xsl:choose>
        <xsl:when test="$month">
          <xsl:value-of select="$month"/>
        </xsl:when>
        <xsl:otherwise>
          <xsl:apply-templates/>
        </xsl:otherwise>
      </xsl:choose>
    </month>
  </xsl:template>

  <xsl:template name="splitMonths">
    <xsl:param name="months"/>
    <xsl:variable name="firstMonth" select="substring-before($months,',')"/>
    <xsl:variable name="month">
      <xsl:choose>
        <xsl:when test="$firstMonth">
          <xsl:value-of select="$firstMonth"/>
        </xsl:when>
        <xsl:otherwise>
          <xsl:value-of select="$months"/>
        </xsl:otherwise>
      </xsl:choose>
    </xsl:variable>
    <xsl:variable name="otherMonths" select="substring-after($months,',')"/>
    <xsl:if test="$month">
      <payload>
        <xsl:apply-templates>
          <xsl:with-param name="month" select="$month"/>
        </xsl:apply-templates>
      </payload>
    </xsl:if>
    <xsl:if test="$otherMonths">
      <xsl:call-template name="splitMonths">
        <xsl:with-param name="months" select="$otherMonths"/>
      </xsl:call-template>
    </xsl:if>
  </xsl:template>

  <xsl:template match="payload">
    <xsl:call-template name="splitMonths">
      <xsl:with-param name="months" select="set/month"/>
    </xsl:call-template>
  </xsl:template>

</xsl:stylesheet>
相关问题