使用JDOM处理XML数据之XSLT篇 
   在java中使用JDOM可以方便的处理XML数据。处理XML数据的方式一般包括三种:直接读取和操作XML数据,使用XSLT把XML转化成网页,使用XSL-FO把XML转化成二进制(PDF)格式。第一种转化的方式已经在上一篇文章中介绍过了(http://www.csdn.net/Develop/read_article.asp?id=20720),这里介绍第二种转化XML的方式:使用XSLT把XML转化成网页。 
要转化XML文挡就要有一个后缀名是.XSL的XSLT文件。例子中用到的XML文件和XSLT文件如下: 
watchlist.xml 
<?xml version="1.0"?> 
<quote-list date="Nov. 4, 2001" time="9:32 AM EST"> 
   <customer first-name="Kurt" last-name="Gabrick" id="9999"/> 
  <quote symbol="SRMC" name="Sierra Monitor Corporation"> 
       <price amount="2.00" currency="USD"/> 
       <price amount="1.05" currency="GBP"/> 
       <price amount="4000.00" currency="MXP"/> 
   </quote> 
  <quote symbol="IBM" name="International Business Machines"> 
       <price amount="135.00" currency="USD"/> 
       <price amount="67.75" currency="GBP"/> 
       <price amount="230000.00" currency="MXP"/> 
   </quote> 
  <quote symbol="ORCL" name="Oracle Corporation"> 
       <price amount="15.00" currency="USD"/> 
       <price amount="7.75" currency="GBP"/> 
       <price amount="30000.00" currency="MXP"/> 
   </quote> 
</quote-list> 
  
watchlist.xsl 
<?xml version="1.0" encoding="UTF-8"?> 
  
<xsl:stylesheet  
               xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 
  
   <xsl:output method="html"  
           doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"  
   /> 
  
<xsl:template match="/"> 
  
<html> 
  
<head><title>Your Watch List</title></head> 
  
<body> 
  
<h1>Your Stock Price Watch List</h1> 
  
<h3>Greetings, Mr. <xsl:value-of select="quote-list/customer[@last-name]"/>!</h3> 
  
<h3>Here are the latest prices on your stocks of interest:</h3> 
  
<p><i> 
Price quotes as of  
  <xsl:value-of select="/quote-list[@time]"/> 
on 
  <xsl:value-of select="/quote-list[@date]"/> 
</i></p> 
  
<table cellpadding="5" cellspacing="0" border="1"> 
<tr> 
  <th>Stock Symbol</th> 
  <th>Company Name</th> 
  <th>Last Price</th> 
  <th>Easy Actions</th> 
</tr> 
<xsl:for-each select="//quote"> 
   <tr> 
       <td><xsl:value-of select="@symbol"/></td> 
       <td><xsl:value-of select="@name"/></td> 
               <xsl select="//quote//price"> 
       <td><xsl:value-of select="@amount/price[@currency=USD]"/></td> 
               </xsl> 
  <td> 
        <a href="aa">buy</a><br/> 
        <a href="sell">sell</a><br/> 
  </td> 
   </tr> 
</xsl:for-each> 
</table> 
  
</body> 
  
</html> 
  
</xsl:template> 
  
</xsl:stylesheet> 
  关于如何针对一个XML文件去写一个XSLT需要去参考别的专门的书籍,在这里不做详细的介绍了。但是一定要记住要正确的按照自己的要求去书写XSLT文件,否则在格式化输出的时候就会产生错误了。 
 
  |