2013-10-20 63 views
0

我需要查找所有书籍,如果该书有多个作者,请在该名称后面写上第一个作者姓名和“et al”。下面是我的代码和第一本书用“JK Rowling等”打印,但不适用于第二本书。用于计算具有相同标记名称的子节点的xpath

这是XML代码

<bookstore> 
<book> 
<title category="fiction">Harry Potter</title> 
<author>J. K. Rowling</author> 
<author>sxdgfds</author> 
<publisher>Bloomsbury</publisher> 
<year>2005</year> 
<price>29.99</price> 
</book> 
<book> 
<title category="fiction">The Vampire Diaries</title> 
<author>L.J. Smith</author> 
<author>sdgsdgsdgdsg</author> 
<publisher>Bloomsbury</publisher> 
<year>2004</year> 
<price>25.99</price> 
</book> 
<book> 
<title category="fiction">The DaVinci Code</title> 
<author>Dan Brown</author> 
<publisher>Bloomsbury</publisher> 
<year>2002</year> 
<price>35.99</price> 
</book> 

这是XSLT代码

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

    <xsl:if test="title[@category='fiction']"> 

      <span style="color:blue;font-weight:bold"><xsl:value-of select="title"/></span><br /> 
      <xsl:choose> 
       <xsl:when test="count(./author)>1"> 
        <span style="color:red;font-style:italic"><xsl:value-of select="author"/></span> 
        <span style="color:red;font-style:italic"> et al</span><br /> 
       </xsl:when> 
       <xsl:otherwise> 
        <span style="color:red;font-style:italic"><xsl:value-of select="author"/></span><br /> 
       </xsl:otherwise> 
      </xsl:choose> 
      <span><xsl:value-of select="price"/></span><br /> 

    </xsl:if> 

    </xsl:for-each> 

我试图算多少作者是有,但好像我在与路径中的问题我已经给了伯爵函数。任何帮助将不胜感激。

回答

1

你的代码似乎没问题,但同样的事情可以表达得更简单。

<xsl:for-each select="//book[price &lt; 30]"> 
    <xsl:if test="title[@category='fiction']"> 
     <span style="color:blue;font-weight:bold"><xsl:value-of select="title"/></span><br /> 
     <span style="color:red;font-style:italic"><xsl:value-of select="author[1]" /></span> 
     <xsl:if test="author[2]"> 
      <span style="color:red;font-style:italic"> et al</span> 
     </xsl:if> 
     <br /> 
     <span><xsl:value-of select="price"/></span><br /> 
    </xsl:if> 
</xsl:for-each> 

上面的代码比你的代码短,但它不是很优雅。这个更好。

<xsl:template match="/"> 
    <xsl:apply-templates select="//book[price &lt; 30 and @category='fiction']" /> 
</xsl:template> 

<xsl:template match="book"> 
    <div class="book"> 
    <div class="title"><xsl:value-of select="title"/></div> 
    <div class="author"> 
     <xsl:value-of select="author[1]" /><xsl:if test="author[2]"> et al</xsl:if> 
    </div> 
    <div class="price"><xsl:value-of select="price"/></div> 
    </div> 
</xsl:template> 
  • 编写能够显示每一本书,像这样的一个通用模板。
  • 通过<xsl:apply-templates>使用它们,而不是用<xsl:for-each>重复自己。
  • 使用CSS来设置输出风格。内联样式很难看。
+0

非常感谢。两个答案都很有效。我想得太过头了,让它变得比实际情况复杂。 – koshi18

相关问题