XSLT实现XML文档转换成HTML文档

来源:互联网 发布:数字电视是网络电视吗 编辑:程序博客网 时间:2024/05/15 23:51

 XML文档描述了数据的结构,并且可以用自定义的标记元素描述数据意义,而且实现了记录数据的功能。如果想要将XML的数据显示在网页页面上,如何做呢?


最简单的方式就是将XML文件直接用浏览器打开,在记事本里写几句简单的代码,例如:

[html] view plain copy
 print?
  1. <?xml version="1.0" encoding="iso-8859-1"?>  
  2. <myDogs>  
  3.    <dog>  
  4.       <name>Casey</name>  
  5.       <age>2</age>  
  6.       <fullBlood>yes</fullBlood>  
  7.       <color>Yellow</color>  
  8.       </dog>  
  9. </myDogs>  


上面的代码保存了一只狗的信息,保存成xml格式,拖到浏览器里运行就可以了,结果是是这样


       但这样的界面不够友好,如果我想用表格显示出信息,如何做到呢?那么可以将XML文档转换成HTML文档,以达到更有好的显示XML数据的目的。

      介绍具体步骤之前介绍下,XSLT(Extensible StyleSheet Language Transmations),是XSL(可扩展样式语言)的一种,是一种基于模版的样式转换语言,说的直接一点就是可以把XML文本转成其他格式的文本,那么一起来看转换的代码:

[html] view plain copy
 print?
  1. <?xml version="1.0" encoding="iso-8859-1"?>  
  2. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">  
  3.   
  4. <xsl:template match="/">  
  5. <html>  
  6. <head>  
  7.     <title>Review of My Dogs</title>  
  8. </head>  
  9. <body>  
  10.     <h4>list of My Dogs</h4>  
  11.       
  12.     <table width="100%" border="1">  
  13.         <thead>  
  14.             <tr>  
  15.             <th>Name</th>  
  16.             <th>Breed</th>  
  17.             <th>Age</th>  
  18.             <th>Full Blood</th>  
  19.             <th>Color</th>  
  20.             </tr>  
  21.         </thead>  
  22.         <tbody>  
  23.             <xsl:apply-templates/>  
  24.         </tbody>  
  25.     </table>  
  26. </body>  
  27. </html>  
  28. </xsl:template>  
  29.   
  30. <xsl:template match="dog">  
  31.     <tr>  
  32.         <td>  
  33.             <strong><xsl:value-of select="name" /></strong>  
  34.         </td>  
  35.         <td><xsl:value-of select="@breed" /></td>  
  36.         <td><xsl:apply-templates select="age" /></td>  
  37.         <td><xsl:value-of select="fullBlood" /> </td>  
  38.         <td><xsl:value-of select="color" /></td>  
  39.     </tr>  
  40.   
  41. </xsl:template>  
  42.   
  43. <xsl:template match="age">  
  44.     <xsl:value-of select="years" />years  
  45.     <xsl:value-of select="months" />months  
  46. </xsl:template>  
  47.   
  48. </xsl:stylesheet>  

将上面的代码写在记事本里,保存成xsl格式,然后再XML文档中引入:
[html] view plain copy
 print?
  1. <?xml version="1.0" encoding="iso-8859-1"?>  
  2. <?xml-stylesheet type="text/xsl" href="mydogs.xsl"?>  
  3.   
  4. <myDogs>  
  5. <dog breed="labrador">  
  6.     <name>morgan</name>  
  7.     <age>  
  8.         <years>1</years>  
  9.         <months>10</months>  
  10.     </age>  
  11.     <fullBlood>yes</fullBlood>  
  12.     <color>Chocolate</color>  
  13. </dog>  
  14. </myDogs>  


运行就可以了,运行结果是这样:


这样显示的界面友好性就提升了。


随着互联网的发展,PHP,Android,unity3D等快速发展,用json比较多,不过xml还是应当学习一下的。

0 0
原创粉丝点击