首页 > 解决方案 > XSLT 递归添加元素

问题描述

我是 XSLT 的新手,并试图转换传入的文件,然后由另一个程序处理。目标是尝试在现有 XML 文件中添加空行,以模拟页面长度,以便其他程序正确处理。我需要计算<line>每个元素之间的<page>元素,如果总数小于 75,则将剩余的行添加为空白。在 XSLT 中递归添加空行的最佳方法是什么?到目前为止,我传入的 XML 如下所示:

<page>
    <line>Some text</line>
    <line>Some text</line>
    <line>Some text</line>
    etc...
</page>

我一直在查看使用节点将事物分组在一起的示例(设置组大小变量):

<xsl:call-template name="file">
     <xsl:with-param name="nodes" select=".|following-sibling::*[not(position() > $pGroupSize - 1)]"/>
</xsl:call-template>

我也一直在寻找关于分段递归的结果,如下例所示:

<xsl:template name="priceSumSegmented">
  <xsl:param name="productList"/>
  <xsl:param name="segmentLength" select="5"/>
  <xsl:choose>
    <xsl:when test="count($productList) > 0">
      <xsl:variable name="recursive_result1">
        <xsl:call-template name="priceSum">
          <xsl:with-param name="productList"
            select="$productList[position() <= $segmentLength]"/>
        </xsl:call-template>
      </xsl:variable>
      <xsl:variable name="recursive_result2">
        <xsl:call-template name="priceSumSegmented">
          <xsl:with-param name="productList"
            select="$productList[position() > $segmentLength]"/>
        </xsl:call-template>
      </xsl:variable>
      <xsl:value-of select="$recursive_result1 + $recursive_result2"/>
    </xsl:when>
    <xsl:otherwise><xsl:value-of select="0"/></xsl:otherwise>
  </xsl:choose> 
</xsl:template>

任何有关解决此问题的最佳方法的帮助将不胜感激。

标签: xsltxslt-1.0

解决方案


我认为你让这变得比它需要的更复杂。即使在 XSLT 1.0 中,您也可以简单地执行以下操作:

<xsl:template match="page">
    <xsl:copy>
        <xsl:copy-of select="line"/>
        <xsl:call-template name="generate-lines">
            <xsl:with-param name="n" select="75 - count(line)"/>
        </xsl:call-template>
    </xsl:copy>
</xsl:template>

<xsl:template name="generate-lines">
    <xsl:param name="n"/>
    <xsl:if test="$n > 0">
        <line/>
        <!-- recursive call -->
        <xsl:call-template name="generate-lines">
            <xsl:with-param name="n" select="$n - 1"/>
        </xsl:call-template>
    </xsl:if>
</xsl:template>

推荐阅读