【问题标题】:Split the values of a Tag using xslt使用 xslt 拆分标签的值
【发布时间】:2012-06-26 12:45:31
【问题描述】:

来源:

  <Data>
     <value>M1,M2,M3,M4,M5,M6</value>
  </Data>

需要显示为

输出:

    <ABCD>
        <value1>M1</value1>
        <value2>M2</value2>
        <value3>M3</value3>
        <value4>M4</value4>
        <value5>M5</value5>
        <value6>M6</value6>
    </ABCD>

XSLT:

我实际上想根据“,”拆分值并将它们放在不同的变量中。 使用 str-split(),我可以将它加载到不同的变量中吗?

【问题讨论】:

    标签: xslt xslt-1.0


    【解决方案1】:

    这个 XSLT 1.0 转换

    <xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:output omit-xml-declaration="yes" indent="yes"/>
     <xsl:strip-space elements="*"/>
    
     <xsl:template match="/*">
      <ABCD>
        <xsl:apply-templates/>
      </ABCD>
     </xsl:template>
    
     <xsl:template match="value/text()" name="split">
      <xsl:param name="pText" select="."/>
      <xsl:param name="pOrd" select="1"/>
    
      <xsl:if test="$pText">
        <xsl:element name="value{$pOrd}">
          <xsl:value-of select=
            "substring-before(concat($pText, ','), ',')"/>
        </xsl:element>
    
        <xsl:call-template name="split">
          <xsl:with-param name="pText" select="substring-after($pText, ',')"/>
          <xsl:with-param name="pOrd" select="$pOrd+1"/>
        </xsl:call-template>
      </xsl:if>
     </xsl:template>
    </xsl:stylesheet>
    

    应用于提供的 XML 文档时:

    <Data>
        <value>M1,M2,M3,M4,M5,M6</value>
    </Data>
    

    产生想要的正确结果

    <ABCD>
       <value1>M1</value1>
       <value2>M2</value2>
       <value3>M3</value3>
       <value4>M4</value4>
       <value5>M5</value5>
       <value6>M6</value6>
    </ABCD>
    

    解释

    1. 递归命名模板,当传递的文本参数变为空字符串时具有停止条件。

    2. 正确使用xsl:elementAVT

    3. 正确使用标准 XPath 函数 substring-before()substring-after

    4. 正确使用 sentinel 来简化代码并提高效率。

    【讨论】:

      【解决方案2】:

      如果您有权访问 EXSLT,则可以使用 str:split()

      <xsl:apply-templates select='str:split(/Data/value, ",")' />
      

      Runnable example here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-20
        • 2017-08-29
        • 1970-01-01
        • 2023-04-04
        • 2013-03-17
        相关资源
        最近更新 更多