XSLT xsl:apply-templates 元素


XSLT xsl:apply-templates 元素

XSLT (Extensible Stylesheet Language Transformations) 用于将 XML 文档从一种形式转换为另一种形式。在 XSLT 中,使用xsl:apply-templates指定将应用哪个模板。xsl:apply-templates 元素是 XSLT 模板中最重要的元素之一,它的作用是根据选择器选择合适的 XML 元素,并将其传递到模板中进一步处理。

语法

<xsl:apply-templates
     select = "选择器"
     mode = "模式"
     priority = "优先级"/>

属性

  • select: 指定选择器,选择器必须是有效的 XPath 表达式,决定哪些节点应该应用模板。
  • mode: 可选属性,指定模式,在同一模板中定义多个匹配规则时,mode 可以帮助区分不同的处理规则。
  • priority: 可选属性,优先级默认为 0,数值越大越先被应用。

用例

考虑以下 XML 文档:

<?xml version="1.0" encoding="utf-8"?>
<root>
    <bookstore>
        <book category="Computer">
            <title lang="en">Java</title>
            <author>Kathy Sierra & Bert Bates</author>
            <year>2005</year>
            <price>29.99</price>
        </book>
        <book category="Computer">
            <title lang="en">Python</title>
            <author>Guido van Rossum</author>
            <year>1991</year>
            <price>19.95</price>
        </book>
        <book category="Romance">
            <title lang="en">Romeo & Juliet</title>
            <author>William Shakespeare</author>
            <year>1597</year>
            <price>5.99</price>
        </book>
    </bookstore>
</root>

XML 文档可以转换为 HTML 页面。可以使用以下 XSLT 转换:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
  <html>
  <body>
    <h2>Books</h2>
    <table>
      <tr>
        <th>Title</th>
        <th>Author</th>
      </tr>
      <xsl:apply-templates select="root/bookstore/book"/>
    </table>
  </body>
  </html>
</xsl:template>

<xsl:template match="book">
  <tr>
    <td><xsl:value-of select="title"/></td>
    <td><xsl:value-of select="author"/></td>
  </tr>
</xsl:template>

</xsl:stylesheet>

在代码中:

  • xsl:apply-templates 具体用于要求查找所有 bookstore 子代的 book 元素,并将其传递到模板中进一步处理。
  • xsl:apply-templates 利用 select 属性来选择所需的节点,调用名为 book 的模板将其处理并生成 HTML 代码。
  • xsl:template 包含模板定义,定义了将 book 元素转换为 table 元素的方式。

转换后输出以下输出结果:

<html>
   <body>
      <h2>Books</h2>
      <table>
         <tbody>
            <tr>
               <td>Java</td>
               <td>Kathy Sierra &amp; Bert Bates</td>
            </tr>
            <tr>
               <td>Python</td>
               <td>Guido van Rossum</td>
            </tr>
            <tr>
               <td>Romeo &amp; Juliet</td>
               <td>William Shakespeare</td>
            </tr>
         </tbody>
      </table>
   </body>
</html>

总结

xsl:apply-templates 元素是 XSLT 模板中最重要的元素之一,它的作用是根据选择器选择合适的 XML 元素,并将其传递到模板中进一步处理。在一个 XSLT模板中,可以包含多个 xsl:apply-templates 元素,以调用不同的模板完成不同的转换任务。