使用XSL的value-of 顯示XML文檔

1.XML文件內容

<?xml version="1.0" encoding="GB2312" ?>
<?xml-stylesheet type="text/xsl" href="book.xsl"?>

<BookLib>
 <Book>
  <Title>Windows程序設計</Title>
  <Author> 好孩子</Author> 
  <PressDate>2000年5月1日</PressDate>
  <Price>49.00元</Price>
 </Book>
 <Book>
  <Title>深入潛出XML</Title>
  <Author> 老虎工作室</Author> 
  <PressDate>2006年10月1日</PressDate>
  <Price>28.00元</Price>
 </Book>
 <Book>
  <Title>人工智能技術導論</Title>
  <Author> 廉師友</Author> 
  <PressDate>2006年5月20日</PressDate>
  <Price>18.00元</Price>
 </Book>
 <Book>
  <Title>IBM彙編程序設計</Title>
  <Author> 沈美名</Author> 
  <PressDate>2000年5月27日</PressDate>
  <Price>34.80元</Price>
 </Book>
</BookLib>

上面的XML文檔定義了一個根節點爲BookLib,有四個Book子元素的樹,其中Book元素又有Title,Author,PressDate,

Price等四個子元素.

2.XSL文檔

<?xml version="1.0" encoding="GB2312"?>
<xsl:stylesheet xmlns:xsl="
http://www.w3.org/TR/WD-xsl">
 <xsl:template match="/">
  <html>
   <xsl:apply-templates/>
  </html>
 </xsl:template>
 <xsl:template match="BookLib">
  <body>
   <xsl:apply-templates/>
  </body>
 </xsl:template>
 <xsl:template match="Book">
  <xsl:apply-templates select="Title | Author"/>
 </xsl:template>
 <xsl:template match="Title">
  <Font size="3" color="#0000FF">
   <BR/>
   <xsl:value-of select="."/>
  </Font>
 </xsl:template>
 <xsl:template match="Author">
  <Font size="3" color="#FF0000">
   <BR/>
   <xsl:value-of select="."/>
  </Font>
 </xsl:template>
 <xsl:template match="PressDate">
  <Font size="3" color="#FF00FF">
   <BR/>
   <xsl:value-of select="."/>
  </Font>
 </xsl:template>
 <xsl:template match="Price">
  <Font size="3" color="#999999">
   <BR/>
   <xsl:value-of select="."/>
  </Font>
 </xsl:template>
</xsl:stylesheet>

XSL文檔的第一個模板一般是匹配根結點的,語法爲match="/"

<xsl:apply-templates/>表示如果有匹配的元素話,依次匹配所有定義的模板

<xsl:template match="Book">
  <xsl:apply-templates select="Title | Author"/>
 </xsl:template>

這幾行表示匹配的元素是Book,對Title或者Author元素如果有匹配的模板則匹配,
<xsl:template match="Title">
  <Font size="3" color="#0000FF">
   <BR/>
   <xsl:value-of select="."/>
  </Font>
這幾行表示如果匹配的元素是Title的話,xsl:value-of select="."這行表示顯示Title的所有子元素,

注意Title可能有子元素,上面的例子Title沒有子元素則顯示Tilte內容

<xsl:template match="Price">
  <Font size="3" color="#999999">
   <BR/>
   <xsl:value-of select="."/>
  </Font>
 </xsl:template>
這幾行表示匹配Price元素,注意在本例中,由於匹配Book元素的模板 只選擇了Tilte和Author元素,所以在本例中

Price元素不會顯示的!!

小結:寫XSL文檔中一般從根結點到具體的元素來一個一個匹配,有點從大到小的味道,大家慢慢體會

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章