XSL 语言

2017-01-18  本文已影响49人  ColdRomantic

1 Introduction

XSL 指扩展样式表语言(EXtensible Stylesheet Language)。
XSLT 是指 XSL 转换(transfer),这里主要来学习如何用XSLT将XML 文档转换为其他文档,比如 XHTML。样例XML文件:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="cdcatalog.xsl"?>
<!--
<?xml-stylesheet type="text/xsl" href="readline.xsl"?>-->
<catalog>
  <cd>
    <title>你好</title>
    <artist>Bob Zhang</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>9.9</price>
    <year>1985</year>
  </cd>
  <cd>
    <title>Happy in the Rain</title>
    <artist>Alice</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>10.00</price>
    <year>1985</year>
  </cd>
  <cd>
    <title>A litte Boy</title>
    <artist>Jhon</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>12.20</price>
    <year>1985</year>
  </cd>
</catalog>

2 语法

XSL 样式表由一个或多套被称为模板(template)的规则组成。
每个模板含有当某个指定的节点被匹配时所应用的规则。

下面来看一个简单的xsl文档:(xmlns 是 XML Namespaces的缩写。)

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
 <html>
 <body>
   <h2>My CD Collection</h2>
   <table border="1">
     <tr bgcolor="#9acd32">
       <th>Title</th>
       <th>Artist</th>
     </tr>
     <tr>
        <td><xsl:value-of select="catalog/cd/title"/></td>
        <td><xsl:value-of select="catalog/cd/artist"/></td>
     </tr>
   </table>
 </body>
 </html>
</xsl:template>

</xsl:stylesheet>

<xsl:stylesheet>,定义此文档是一个 XSLT 样式表文档(连同版本号和 XSLT 命名空间属性)

      <xsl:for-each select="catalog/cd">
      <tr>
        <td><xsl:value-of select="title"/></td>
        <td><xsl:value-of select="artist"/></td>
      </tr>
      </xsl:for-each>

在for-each中过滤,语法: [artist='Bob Dylan']
合法的比较运算符:
= (等于) != (不等于) < (小于) > (大于)

   <xsl:for-each select="catalog/cd[artist='Bob Dylan']">
   <tr>
      <td><xsl:value-of select="title"/></td>
      <td><xsl:value-of select="artist"/></td>
   </tr>
   </xsl:for-each>
      <xsl:for-each select="catalog/cd">
      <xsl:sort select="artist"/>
      <tr>
        <td><xsl:value-of select="title"/></td>
        <td><xsl:value-of select="artist"/></td>
      </tr>
      </xsl:for-each>
上一篇 下一篇

猜你喜欢

热点阅读