Brendon Rother
Brendon Rother

Reputation: 119

XSL count number of specific element

So I'm trying to print slightly different text depending on how many <author> elements there are in a parent element. The code that is giving me trouble is the when xsl code

<?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>

Upvotes: 0

Views: 1233

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117165

The expression:

count(//author)

counts the authors in the entire document. To count the authors of the current book - i.e. in the context of:

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

use:

count(author)

assuming all authors are children of book.

--
BTW, you could simplify this by always outputting the name of the first author, and adding "et al." if there are more than one.

Upvotes: 2

Related Questions