使用XSL的value-of 显示XML文档

来源:互联网 发布:数据接口系统开发方案 编辑:程序博客网 时间:2024/06/05 16:24

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文档中一般从根结点到具体的元素来一个一个匹配,有点从大到小的味道,大家慢慢体会

原创粉丝点击