核心标签
1. <xsl:value-of>
作用:提取指定XML节点的文本内容,输出到结果文档。
<!-- 直接取出第一个catalog/cd下title的值(无循环只会获取第一条) -->
<xsl:value-of select="catalog/cd/title" />Code language: HTML, XML (xml)
不搭配<xsl:for-each>循环时,仅匹配第一条节点,无法遍历全部数据。
2. <xsl:for-each>
作用:循环遍历一组匹配的XML节点,批量处理多条数据。
<xsl:for-each select="class/student">
<li><xsl:value-of select="name"/>;<xsl:value-of select="age"/></li>
</xsl:for-each>Code language: HTML, XML (xml)
XPath过滤语法
在select路径后使用[条件]筛选节点,实现数据过滤
<!-- 只输出artist等于Bob Dylan的cd记录 -->
<xsl:for-each select="catalog/cd[artist='Bob Tom']">Code language: HTML, XML (xml)
支持的运算符
| 运算符 | XPath写法 | 含义 |
|---|---|---|
| = | = | 等于 |
| != | != | 不等于 |
| < | < | 小于(不能直接写<,必须转义) |
| > | > | 大于(不能直接写>,必须转义) |
例如筛选价格小于10的CD
<xsl:for-each select="catalog/cd[price < 10]">Code language: HTML, XML (xml)
前面的例子
student.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>
</head>
<body>
<ul>
<!-- 遍历所有student节点 -->
<xsl:for-each select="class/student">
<li><xsl:value-of select="name"/>;<xsl:value-of select="age"/></li>
</xsl:for-each>
</ul>
</body>
</html>
</xsl:template>
</xsl:stylesheet>Code language: HTML, XML (xml)
配套XML(student.xml)
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="student.xsl"?>
<class>
<student>
<name>Jack</name>
<age>16</age>
</student>
<student>
<name>Jim</name>
<age>12</age>
</student>
</class>Code language: HTML, XML (xml)
增加过滤
只输出年龄大于14岁的学生
<xsl:for-each select="class/student[age > 14]">
<li><xsl:value-of select="name"/>;<xsl:value-of select="age"/></li>
</xsl:for-each>Code language: HTML, XML (xml)