0

私はすべての本を見つける必要があり、本に複数の著者がいる場合は、最初の著者名とその名前の後に「et al」を書きます。以下は私のコードで、最初の本は「JK Rowling et al」で印刷されますが、機能しません二冊目に。

これは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>

何人の著者がいるかを数えようとしていましたが、count 関数に与えたパスに問題があるようです。

4

1 に答える 1

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 を使用して出力のスタイルを設定します。インライン スタイルは醜いです。
于 2013-10-20T06:17:42.693 に答える