2014-10-11 64 views
0

所以我試圖打印稍微不同的文本,具體取決於父元素中有多少個<author>元素。是給我找麻煩的代碼是當XSL代碼特定元素的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> 

回答

2

表達:

count(//author) 

計數在整個文檔中的作者。要統計當前本書的作者 - 也就是在上下文:

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

使用:

count(author) 

假設所有的作家都書的孩子。

-
順便說一句,您可以通過始終輸出第一個作者的名稱並添加「et al」來簡化此操作。如果有多個。