如何使用 <xsl:template match=""> 匹配作者

How can I use <xsl:template match=""> to match the author

我正在尝试使用 XML 和 XSL (XSLT) 生成 HTML 文件。我想显示某个作者 (EX "Mario Vargas Llosa") 所写的所有书籍。我如何使用 xsl:template 中的匹配属性来做到这一点?

XML 代码:

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet href="template.xsl" type="text/xsl" ?>
<library>
  <book>
    <title language="es">La vida está en otra parte</title>
    <author>Milan Kundera</author>
    <publishDate year="1973"/>
  </book>
  <book>
    <title language="es">Pantaleón y las visitadoras</title>
    <author>Mario Vargas Llosa</author>
    <publishDate year="1973"/>
  </book>
  <book>
    <title language="es">Conversación en la catedral</title>
    <author>Mario Vargas Llosa</author>
    <publishDate year="1969"/>
  </book>
  <book>
    <title language="en">Poems</title>
    <author>Edgar Allan Poe</author>
    <publishDate year="1890"/>
  </book>  
  <book>
    <title language="fr">Les Miserables</title>
    <author>Victor Hugo</author>
    <publishDate year="1862"/>
  </book>  
  <book>
    <title language="es">Plenilunio</title>
    <author>Antonio Muñoz Molina</author>
    <publishDate year="1997"/>
  </book>  
</library>

XSLT 代码:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
    <html>
    <head>
        <link rel="stylesheet" href="style.css"/>
    </head>
        <body>
            <xsl:for-each select="library/book">
                <h1>Title: 
                    <xsl:value-of select="title"/>
                </h1>
                <p>
                    <strong>Author: </strong>
                    <xsl:value-of select="author"/>
                </p>
                <p>
                    <strong>Publishing date: </strong>
                    <xsl:value-of select="publishDate/@year"/>
                </p>
            </xsl:for-each>
        </body>
    </html>
</xsl:template>

提前致谢。

XSLT 中的一行修改。您需要添加谓词。

<xsl:for-each select="library/book[author='Mario Vargas Llosa']">

将您的 XSLT 文件更改为

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <html>
        <head>
            <link rel="stylesheet" href="style.css"/>
        </head>
            <body>
                <xsl:for-each select="library/book[author='Mario Vargas Llosa']">
                    <h1>Title: 
                        <xsl:value-of select="title"/>
                    </h1>
                    <p>
                        <strong>Author: </strong>
                        <xsl:value-of select="author"/>
                    </p>
                    <p>
                        <strong>Publishing date: </strong>
                        <xsl:value-of select="publishDate/@year"/>
                    </p>
                </xsl:for-each>
            </body>
        </html>
    </xsl:template>
</xsl:stylesheet>

并且您的 xsl:for-each 将遍历 "Mario Vargas Llosa" 的所有 <book>。所以输出(在你的浏览器中)将是