<xsl:apply-templates> 的範例
此範例中的樣式表會將 XML 中的客戶資料格式化為 HTML <TABLE> 項目。 在輸出資料表中,每個資料列都代表一個客戶,而資料行則代表客戶的姓名、地址與電話號碼。 <xsl:sort> 項目會依據縣市來排序客戶,而所有來自於同一縣市的客戶則會依據姓名排序。
XML 檔 (customers.xml)
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="applyt.xsl" ?>
<customers>
<customer>
<name>John Smith</name>
<address>123 Oak St.</address>
<state>WA</state>
<phone>(206) 123-4567</phone>
</customer>
<customer>
<name>Zack Zwyker</name>
<address>368 Elm St.</address>
<state>WA</state>
<phone>(206) 423-4537</phone>
</customer>
<customer>
<name>Albert Aikens</name>
<address>368 Elm St.</address>
<state>WA</state>
<phone>(206) 423-4537</phone>
</customer>
<customer>
<name>Albert Gandy</name>
<address>6984 4th St.</address>
<state>WA</state>
<phone>(206) 433-4547</phone>
</customer>
<customer>
<name>Peter Furst</name>
<address>456 Pine Av.</address>
<state>CA</state>
<phone>(209) 765-4321</phone>
</customer>
<customer>
<name>Dan Russell</name>
<address>9876 Main St.</address>
<state>PA</state>
<phone>(323) 321-7654</phone>
</customer>
</customers>
XSLT 檔 (applyt.xsl)
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:template match="/">
<HTML>
<BODY>
<TABLE border="1" cellspacing="0" cellpadding="2">
<xsl:apply-templates select="customers/customer">
<xsl:sort select="state"/>
<xsl:sort select="name"/>
</xsl:apply-templates>
</TABLE>
</BODY>
</HTML>
</xsl:template>
<xsl:template match="customer">
<TR>
<xsl:apply-templates select="name" />
<xsl:apply-templates select="address" />
<xsl:apply-templates select="state" />
<xsl:apply-templates select="phone" />
<xsl:apply-templates select="phone" mode="accountNumber"/>
</TR>
</xsl:template>
<xsl:template match="name">
<TD STYLE="font-size:14pt font-family:serif">
<xsl:apply-templates />
</TD>
</xsl:template>
<xsl:template match="address">
<TD> <xsl:apply-templates /> </TD>
</xsl:template>
<xsl:template match="state">
<TD> <xsl:apply-templates /> </TD>
</xsl:template>
<xsl:template match="phone">
<TD> <xsl:apply-templates /> </TD>
</xsl:template>
<xsl:template match="phone" mode="accountNumber">
<TD STYLE="font-style:italic">
1-<xsl:value-of select="."/>-001
</TD>
</xsl:template>
</xsl:stylesheet>
輸出
此為格式化輸出:
此為處理器輸出:
<HTML>
<BODY>
<TABLE border="1" cellspacing="0" cellpadding="2">
<TR>
<TD STYLE="font-size:14pt font-family:serif">Peter Furst</TD>
<TD>456 Pine Av.</TD>
<TD>CA</TD>
<TD>(209) 765-4321</TD>
<TD STYLE="font-style:italic">
1-(209) 765-4321-001
</TD>
</TR>
<TR>
<TD STYLE="font-size:14pt font-family:serif">Dan Russell</TD>
<TD>9876 Main St.</TD>
...
</TR>
</TABLE>
</BODY>
</HTML>