XSL在内部循环下计算xml节点

时间:2017-05-06 11:06:00

标签: xml xslt

##我有我的xml如下所示,我想得到我在下面尝试过的标题节点的数量,但我总是算作1,因为它在for-each循环中              

    <xsl:if test="$countryVal !='' and $countryVal = 'USA'">
<tr>
      <td><xsl:value-of select="title"/></td>
      <h3>Count of titles <xsl:value-of select="count(catalog/cd/title)"/></h3>
    </tr>
    </xsl:if>
    </xsl:for-each>

<catalog>
  <cd>
    <title>USD</title>
    <artist>Bob Dylan</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>10.90</price>
    <year>1985</year>
  </cd>
  <cd>
    <title>USD</title>
    <artist>Bonnie Tyler</artist>
    <country>USA</country>
    <company>CBS Records</company>
    <price>9.90</price>
    <year>1988</year>
  </cd>
  <cd>
    <title>CAD</title>
    <artist>Dolly Parton</artist>
    <country>CAN</country>
    <company>RCA</company>
    <price>9.90</price>
    <year>1982</year>
  </cd>
  <cd>
    <title>USD</title>
    <artist>Gary Moore</artist>
    <country>USA</country>
    <company>Virgin records</company>
    <price>10.20</price>
    <year>1990</year>
  </cd>
</catalog>

xml shared是big xml的一部分,共享它的片段。 有什么指针吗?

1 个答案:

答案 0 :(得分:1)

我建议您使用变量来保存已过滤的节点集 - 这样您只需要应用一次过滤:

<xsl:variable name="eligible-cds" select="/catalog/cd[country='USA']" />

然后你可以这样做:

<xsl:for-each select="$eligible-cds">
    <tr>
        <td><xsl:value-of select="title"/></td>
    </tr>
</xsl:for-each>
<h3>Count of titles <xsl:value-of select="count($eligible-cds)"/></h3>