天天看點

XSLT實作XML文檔轉換成HTML文檔

       XML文檔描述了資料的結構,并且可以用自定義的标記元素描述資料意義,而且實作了記錄資料的功能。如果想要将XML的資料顯示在網頁頁面上,如何做呢?

最簡單的方式就是将XML檔案直接用浏覽器打開,在記事本裡寫幾句簡單的代碼,例如:

<?xml version="1.0" encoding="iso-8859-1"?>
<myDogs>
   <dog>
      <name>Casey</name>
      <age>2</age>
      <fullBlood>yes</fullBlood>
      <color>Yellow</color>
      </dog>
</myDogs>
           

上面的代碼儲存了一隻狗的資訊,儲存成xml格式,拖到浏覽器裡運作就可以了,結果是是這樣

XSLT實作XML文檔轉換成HTML文檔

       但這樣的界面不夠友好,如果我想用表格顯示出資訊,如何做到呢?那麼可以将XML文檔轉換成HTML文檔,以達到更有好的顯示XML資料的目的。

      介紹具體步驟之前介紹下,XSLT(Extensible StyleSheet Language Transmations),是XSL(可擴充樣式語言)的一種,是一種基于模版的樣式轉換語言,說的直接一點就是可以把XML文本轉成其他格式的文本,那麼一起來看轉換的代碼:

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

<xsl:template match="/">
<html>
<head>
	<title>Review of My Dogs</title>
</head>
<body>
	<h4>list of My Dogs</h4>
	
	<table width="100%" >
		<thead>
			<tr>
			<th>Name</th>
			<th>Breed</th>
			<th>Age</th>
			<th>Full Blood</th>
			<th>Color</th>
			</tr>
		</thead>
		<tbody>
			<xsl:apply-templates/>
		</tbody>
	</table>
</body>
</html>
</xsl:template>

<xsl:template match="dog">
	<tr>
		<td>
			<strong><xsl:value-of select="name" /></strong>
		</td>
		<td><xsl:value-of select="@breed" /></td>
		<td><xsl:apply-templates select="age" /></td>
		<td><xsl:value-of select="fullBlood" /> </td>
		<td><xsl:value-of select="color" /></td>
	</tr>

</xsl:template>

<xsl:template match="age">
	<xsl:value-of select="years" />years
	<xsl:value-of select="months" />months
</xsl:template>

</xsl:stylesheet>
           

将上面的代碼寫在記事本裡,儲存成xsl格式,然後再XML文檔中引入:

<?xml version="1.0" encoding="iso-8859-1"?>
<?xml-stylesheet type="text/xsl" href="mydogs.xsl" target="_blank" rel="external nofollow" ?>

<myDogs>
<dog breed="labrador">
	<name>morgan</name>
	<age>
		<years>1</years>
		<months>10</months>
	</age>
	<fullBlood>yes</fullBlood>
	<color>Chocolate</color>
</dog>
</myDogs>
           

運作就可以了,運作結果是這樣:

XSLT實作XML文檔轉換成HTML文檔

這樣顯示的界面友好性就提升了。