美文网首页
XSL 语言

XSL 语言

作者: ColdRomantic | 来源:发表于2017-01-18 14:08 被阅读49次

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 命名空间属性)

  • (1) <xsl:template> 元素
    <xsl:template> 元素定义了一个模板。
    而 match="/" 属性则把此模板与 XML 源文档的根相联系。
  • (2) <xsl:value-of> 元素
    元素用于提取某个选定节点的值,并把值添加到转换的输出流中。
    select 属性的值是一个 XPath 表达式。此表达式的工作方式类似于定位某个文件系统。
  • (3) <xsl:for-each> 元素
    <xsl:for-each> 元素可用于选取指定的节点集中的每个 XML 元素。
      <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>
  • (4) <xsl:sort> 元素
    如需对结果进行排序,只要简单地在 XSL 文件中的 <xsl:for-each> 元素内部添加一个 <xsl:sort> 元素。
      <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>

相关文章

网友评论

      本文标题:XSL 语言

      本文链接:https://www.haomeiwen.com/subject/rtzvbttx.html