假設我們有以下範例XML檔案:students.xml,它需要轉換為格式良好的HTML文件。
檔案:students.xml 的內容如下 -
<?xml version = "1.0"?>
<class>
<student rollno = "10010">
<firstname>Machine</firstname>
<lastname>Lee</lastname>
<nickname>Machine</nickname>
<marks>85</marks>
</student>
<student rollno = "10020">
<firstname>Max</firstname>
<lastname>Su</lastname>
<nickname>Maxsu</nickname>
<marks>95</marks>
</student>
<student rollno = "10030">
<firstname>Yii</firstname>
<lastname>Bai</lastname>
<nickname>Yiibai</nickname>
<marks>90</marks>
</student>
</class>
需要為上面的XML文件定義一個XSLT樣式表文件,以滿足以下條件 -
建立一個XSLT文件以滿足上述要求,將其命名為students.xsl,並將其儲存在students.xml所在的同一個目錄位置。
檔案:students.xsl -
<?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>Students</h2>
<table border = "1">
<tr bgcolor = "#3498db">
<th>Roll No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Nick Name</th>
<th>Marks</th>
</tr>
<!-- for-each處理指令
查詢與XPath表示式匹配的每個元素
-->
<xsl:for-each select="class/student">
<tr>
<td>
<!-- value-of處理指令
處理與XPath表示式匹配的元素的值
-->
<xsl:value-of select = "@rollno"/>
</td>
<td><xsl:value-of select = "firstname"/></td>
<td><xsl:value-of select = "lastname"/></td>
<td><xsl:value-of select = "nickname"/></td>
<td><xsl:value-of select = "marks"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
使用以下xml-stylesheet
標記更新student.xml文件。 將href
值設定為:students.xsl -
<?xml version = "1.0"?>
<?xml-stylesheet type = "text/xsl" href = "students.xsl"?>
<class>
...
</class>
加入樣式檔案students.xsl,更新檔案:students.xml ,內容如下所示 -
<?xml version = "1.0"?>
<?xml-stylesheet type = "text/xsl" href = "students.xsl"?>
<class>
<student rollno = "10010">
<firstname>Machine</firstname>
<lastname>Lee</lastname>
<nickname>Machine</nickname>
<marks>85</marks>
</student>
<student rollno = "10020">
<firstname>Max</firstname>
<lastname>Su</lastname>
<nickname>Maxsu</nickname>
<marks>95</marks>
</student>
<student rollno = "10030">
<firstname>Yii</firstname>
<lastname>Bai</lastname>
<nickname>Yiibai</nickname>
<marks>90</marks>
</student>
</class>
在瀏覽器中開啟上面檔案:student.xml,效果如下所示 -