浅析XSLT(Extensible Stylesheet Language Tranform)

题记:XML将数据的传输和展现分离,专注与数据的传输,XSLT是将数据转化为html来显示.如果是css是html的样式语言的话,xslt就是xml的样式语言.

1.XLST与XML
声明为xlst文件:
<?xml version = "1.0" encoding = "UTF-8" ?>
<xsl:stylesheet version = "1.0" xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">

xml文件引入xls文件:
<?xml-stylesheet type="text/xsl" href="test.xsl" ?>

2.XLST语法:
  • <xsl:template match=""/>:声明使用的XML文件片段, match="/"为全文
  • <xsl:for-each select=""/>: 搜索对应的节点,相当于selectNodes.
  • <xsl:value-of sleect=""/>: 取节点指,相当于node.getText()
  • <xsl:if test="node[condition]"/>: 条件查询
  • <xsl:choose><xsl:when test=""/><xsl:otherwise/></xsl:choose>: 条件遍历,相当于switch.

其他语法请参考xslt教程.

3.XSLT例子
xml文件:
<?xml version = "1.0" encoding = "UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="test.xsl" ?>
<bookstore>
<book>
	<name>Regular Express</name>
	<price>100</price>
	<publisher>OReilly</publisher>
</book>
<book>
	<name>Header First Java</name>
	<price>50</price>
	<publisher>OReilly</publisher>
</book>
<book>
	<name>Header First Design Pattern</name>
	<price>80</price>
	<publisher>OReilly</publisher>
</book>
<book>
	<name>Header First EJB</name>
	<price>90</price>
	<publisher>OReilly</publisher>
</book>
</bookstore>


xsl文件
<?xml version = "1.0" encoding = "UTF-8" ?>
<xsl:stylesheet version = "1.0" xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>
<head>
	<title>Test XSLT</title>
</head>
<body>
<table border = "1">
	<tr bgcolor="#9acd32">
      <th align="left">Name</th>
      <th align="left">Price</th>
      <th align="left">Publisher</th>
    </tr>
    <xsl:for-each select="/bookstore/book">
    <xsl:if test="price > 80">
      <tr bgcolor="red">
      	<td><xsl:value-of select="name"/></td>
      	<td><xsl:value-of select="price"/></td>
      	<td><xsl:value-of select="publisher"/></td>
      </tr>
     </xsl:if>
     <xsl:choose>
     	<xsl:when test="price > 60">
    	  <tr bgcolor="orange">
	      	<td><xsl:value-of select="name"/></td>
	      	<td><xsl:value-of select="price"/></td>
	      	<td><xsl:value-of select="publisher"/></td>
	      </tr>
     	</xsl:when>
     	<xsl:otherwise>
     	 <tr bgcolor="grey">
	      	<td><xsl:value-of select="name"/></td>
	      	<td><xsl:value-of select="price"/></td>
	      	<td><xsl:value-of select="publisher"/></td>
	      </tr>
     	</xsl:otherwise>
     </xsl:choose>
    </xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
.

你可能感兴趣的:(java,xml,css,ejb,XSL)