XSL计数特定元素的数量

时间:2014-10-11 13:40:07

标签: xml xslt count xsl-choose

所以我尝试根据父元素中有多少<author>个元素来打印稍微不同的文本。给我带来麻烦的代码是xsl代码

<?xml version="1.0" standalone="no" ?>
<?xml-stylesheet publisher="text/xsl" href="books3.xsl"?>
<books>
    <book>
        <title type="fiction">HG</title>
        <author>Test</author>
        <publisher>Junk</publisher>
        <year>2001</year>
        <price>29</price>
    </book>
    <book>
        <title type="fiction">HP</title>
        <author>Test1</author>
        <author>Test1</author>
        <publisher>Junk1</publisher>
        <year>2002</year>
        <price>29</price>
    </book>
    <book>
        <title type="fiction">HG</title>
        <author>Test</author>
        <publisher>Junk</publisher>
        <year>2001</year>
        <price>40</price>
    </book>
</books>

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output  method="html" indent="yes" version="4.0" />   
  <xsl:template match="/">
    <div>
      <xsl:for-each select="//book[price &lt; 30]">
        <span id="title"><xsl:value-of select="title"/></span>
        <xsl:choose>
            <xsl:when test="count(//author) &gt; 1">
                <span id="author"><xsl:value-of select="author"/> et al</span>
            </xsl:when>
            <xsl:when test="count(//author) = 1 ">
                <span id="author"><xsl:value-of select="author"/></span>
            </xsl:when>
        </xsl:choose>
        <span id="price"><xsl:value-of select="price"/></span>
      </xsl:for-each>
    </div>
  </xsl:template>
</xsl:stylesheet>

1 个答案:

答案 0 :(得分:2)

表达式:

count(//author)

统计整个文档中的作者。计算当前书籍的作者 - 即在以下情况下:

<xsl:for-each select="//book[price &lt; 30]">

使用:

count(author)

假设所有作者都是书的孩子。

-
顺便说一句,你可以通过输出第一作者的名字并添加“等”来简化这一过程。如果有多个。