每个循环节点上的XSLT,输出包含特定元素的先前节点的数量

时间:2013-05-14 19:04:35

标签: xslt count nodes

鉴于此XML

<Employee>
  <Record>
    <ID>1</ID>
    <Amount>10</Amount>
  </Record>
  <Record>
    <ID>2</ID>
    <Amount>0</Amount>
  </Record>
  <Record>
    <ID>3</ID>
    <Amount>0</Amount>
  </Record>
  <Record>
    <ID>4</ID>
    <Amount>20</Amount>
  </Record>
  <Record>
    <ID>5</ID>
    <Amount>50</Amount>
  </Record>
  <Record>
    <ID>6</ID>
    <Amount>0</Amount>
  </Record>
  <Record>
    <ID>7</ID>
    <Amount>40</Amount>
  </Record>
</Employee>

使用XSLT 1.0,我希望输出如下:

Zero amount node: 0
Zero amount node: 0
Zero amount node: 1
Zero amount node: 2
Zero amount node: 2
Zero amount node: 2
Zero amount node: 3

我想在for-each节点中使用Record并循环,并在每次迭代时输出包含零Amount的前面节点的数量。

我的XSLT:     

  <xsl:output method="text" indent="no"/>

  <xsl:template match="/">

  <xsl:for-each select="Employee/Record">

    <xsl:variable name="amount-so-far" select=". | preceding-sibling::Record"/>
    <xsl:variable name="amount-so-far-not-zero" select="$amount-so-far[not('0' = preceding-sibling::Record/Amount)]"/>
    <xsl:value-of select="count($amount-so-far-not-zero)"/>

    <xsl:text>
</xsl:text>

</xsl:for-each>

</xsl:template>
</xsl:stylesheet>

1 个答案:

答案 0 :(得分:1)

尝试使用此XSLT获取所需的输出:

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

  <xsl:template match="Employee">
    <xsl:for-each select="Record">
      <xsl:value-of select="concat('Zero amount node: ', count(preceding-sibling::Record[Amount='0']))"/><xsl:text>

      </xsl:text>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>