XSLT <template>学习笔记

简介

在XSLT中,<template>元素定义了一个模板,用于指定如何将输入文档转换为输出文档。模板可以匹配特定的XML节点,并提供大量的灵活性和控制。

语法

下面是一个基本的<template>元素的语法:

Copy Code
<xsl:template match="pattern"> <!-- template content --> </xsl:template>

其中,match属性用于匹配XML节点的模式,template content则包含了转换后输出的内容。

实例

下面是一个简单的实例,演示了如何使用<template>元素将输入XML转换为输出HTML:

xmlCopy Code
<?xml version="1.0" encoding="UTF-8"?> <catalog> <book id="bk101"> <author>Gambardella, Matthew</author> <title>XML Developer's Guide</title> <genre>Computer</genre> <price>44.95</price> <publish_date>2000-10-01</publish_date> <description>An in-depth look at creating applications with XML.</description> </book> <book id="bk102"> <author>Ralls, Kim</author> <title>Midnight Rain</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2000-12-16</publish_date> <description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description> </book> </catalog>
Copy Code
<?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>Book Catalog</h2> <table border="1"> <tr> <th>Title</th> <th>Author</th> <th>Genre</th> <th>Price</th> <th>Publish Date</th> <th>Description</th> </tr> <xsl:for-each select="catalog/book"> <tr> <td><xsl:value-of select="title"/></td> <td><xsl:value-of select="author"/></td> <td><xsl:value-of select="genre"/></td> <td><xsl:value-of select="price"/></td> <td><xsl:value-of select="publish_date"/></td> <td><xsl:value-of select="description"/></td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>

在上面的实例中,我们首先定义了一个<template>元素来匹配XML文档的根节点。接着,在该模板中,我们创建了一个HTML文档,并使用for-each语句遍历了XML文档中的所有<book>节点。对于每个<book>节点,我们都创建了一行数据,并从<title>、<author>、<genre>、<price>、<publish_date>和<description>子节点中提取了内容,并将其插入到HTML表格中。

结论

XSLT的<template>元素为XML文档的转换提供了极大的灵活性和控制。我们可以通过定义不同的模板,来匹配不同的XML节点,并针对每个节点提供特定的输出。这种方式使得XSLT成为了一种非常强大和实用的XML转换工具。