For循环vs. apply-templates

问题描述

| 我最近开始对某些XML文档使用XSLT,但我有一些疑问。我在下面添加代码。在代码中,我有一个与电子书元素匹配的模板。然后,我想列出所有写这本书的作者。我使用for每个循环,但也可以将模板应用于该循环。我什么时候使用循环和何时使用模板看不到清晰的界线。 另一个问题是,当您现在正在编写该元素的其他子元素不存在时,只说apply-templates是正常的。对于与文档根目录匹配的模板,我说的是apply-templates。然后它找到了唯一的电子书,但是我可以有一个“ books”元素来区分“常规”书和电子书,然后只列出这些书的字符数据。如果我只想在最终文档中使用电子书,那么我将需要编写apply-templates select = \“ ebooks \”。那么,这是否取决于您对文档的了解程度呢? 谢谢,这是我的代码(这只是为了练习): XML:
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<?xml-stylesheet type=\"text/xsl\" href=\"ebooks.xsl\"?>
<ebooks>
    <ebook>
        <title>Advanced Rails Recipes: 84 New Ways to Build Stunning Rails Apps</title>
        <authors>
            <author><name>Mike Clark</name></author>
        </authors>
        <pages>464</pages>
        <isbn>978-0-9787-3922-5</isbn>
        <programming_language>Ruby</programming_language>
        <date>
            <year>2008</year>
            <month>5</month>
            <day>1</day>
        </date>
        <publisher>The Pragmatic Programmers</publisher>
    </ebook>
    ...
XSLT:
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">

    <xsl:template match=\"/\">
        <html>
            <head>
                <title>Library</title>
            </head>
            <body>
                <xsl:apply-templates />            
            </body>
        </html>    
    </xsl:template>

    <xsl:template match=\"ebooks\">
        <h1>Ebooks</h1>
        <xsl:apply-templates>
            <xsl:sort select=\"title\"/>
        </xsl:apply-templates>
    </xsl:template>

    <xsl:template match=\"ebook\">
        <h3><xsl:value-of select=\"title\"/></h3>
        <xsl:apply-templates select=\"date\" />

        <xsl:for-each select=\"authors/author/name\">
            <b><xsl:value-of select=\".\"/>,</b>
        </xsl:for-each>
    </xsl:template>

    <xsl:template match=\"date\">
        <table border=\"1\">
            <tr>
                <th>Day</th>
                <th>Month</th>
                <th>Year</th>
            </tr>
            <tr>
                <td><xsl:value-of select=\"day\"/></td>
                <td><xsl:value-of select=\"month\"/></td>
                <td><xsl:value-of select=\"year\"/></td>
            </tr>
        </table>
    </xsl:template>

</xsl:stylesheet>
    

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)