XSLT学习(转载)

 不太会进行理论的介绍,就拿例子来进行初步的介绍吧!呵呵,望大家见谅!欢迎大家给提意见!
      先看一段XML文档


<?xml version="1.0" encoding="utf-8" ?>
<Authors>
  
<Author>
    
<AuthorName id="1">Author1</AuthorName>
    
<AuthorAddress>Address1</AuthorAddress>
    
<AuthorEmail>EMail1</AuthorEmail>
  
</Author>
  
<Author>
    
<AuthorName id="2">Author2</AuthorName>
    
<AuthorAddress>Address2</AuthorAddress>
    
<AuthorEmail>EMail2</AuthorEmail>
  
</Author>
  
<Author>
    
<AuthorName>Author3</AuthorName>
    
<AuthorAddress>Address3</AuthorAddress>
    
<AuthorEmail>EMail3</AuthorEmail>
  
</Author>
</Authors>

      这段文档经过下面的XSLT文件

<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet version="1.0"
    xmlns:xsl
="http://www.w3.org/1999/XSL/Transform">
  
<xsl:output method="xml"/>

  
<xsl:template match="/">
    
<html>
      
<body>
        
<table border="1px">
        
<xsl:apply-templates/>
        
</table>
      
</body>
    
</html>
  
</xsl:template>
  
<xsl:template match="Author">
    
<xsl:value-of select="."/>
  
</xsl:template>
</xsl:stylesheet>

转换会得到下面的xml文件


<?xml version="1.0" encoding="utf-8"?>
<html>
  
<body>
    
<table border="1px">

      Author1
      Address1
      EMail1


      Author2
      Address2
      EMail2


      Author3
      Address3
      EMail3

    
</table>
  
</body>
</html>


对于这个.xsl文件:
<xsl:stylesheet>和<xsl:stylesheet>表示这个文档是XSLT样式表,version自然代表使用的版本,xmlns:xsl是标准的XML命名空间声明。所有的XSLT文档必须使用这个URI作为命名空间前缀。当然可以定义自己的命名空间,这样可以避免不同的元素,属性命名的冲突。当然xsl是习惯性的前缀,比较容易理解。也可以使用自定义的前缀名。

<xsl:output method="xml/>用于控制XSLT转换的输出格式(可以指定为xml.html.text),还有其他的可选属性(如version来指明输出xml文档的版本 Encoding指定编码方式)。

<xsl:template match="/"></xsl:template>定义XSLT模板规则,是XSLT中最主要的部分。XSLT代码最终的目的是将XML文档按照模板定义的规则进行输出。属性match用来指定匹配的模式,"/"代表选择根节点,返回的将是根节点后代的集合,具体语法将在下一篇文章中介绍。其它可选属性如name可以定义模板的名字,priority定义模板的优先级,mode定义模板的模式。               name:作为一个模板的标识,就像一个人的名字。如果我们指定一个模板的name="NameXX"那么我们可以通过<xsl:call-template name="NameXX"/>来调用它。本例中<xsl:apply-templates/>就可以用<xsl:call-template name="NameXX"/>代替。               priority指定模板的优先级。                  mode:相当于选择的作用,如果一个模板的mode被设定为"Y",那么<xsl:apply-templates mode="X"/>只会选择与X同名的template,mode值为其它的template将不会得到使用。

<xsl:value-of select="."/>是选择当前节点的值。因为"."匹配当前节点,返回值为当前节点以及其子节点集,所以所有的子节点值会被选择出来。

转自:http://www.cnblogs.com/jingtao/archive/2007/07/27/833773.html 

原文地址:https://www.cnblogs.com/johnwonder/p/1949690.html