XSL即可扩展的样式表文件。 可以格式化xml的显示,也可以将xml转换成需要的另一种格式。 学习XSL必须熟悉XPath。XSL和XPath一样简单强大,容易学习。 1. XSL既然可以格式化xml的显示样式,我们先来看如何在xml中引用xsl文件 如下代码示例: <?xml version="1.0" encoding="utf-8"?> <?xml-stylesheet type="text/xsl" href="url.xsl"?> 只需在xml文件的文档声明后面添加<?xml-stylesheet type=”text/xsl” href=”url.xsl”?>即可 2. XSL的格式 XSL也是一个标准的xml文件,它以xml文档声明开始,根元素必须是xsl:styleshee,同时根元素必须有version属性指定xsl的版本,和xmlns:xsl=” http://www.w3.org/1999/XSL/Transform”指定xsl命名空间,如下示例 <?xml version="1.0" encoding="encoding”?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 3. Xsl要点 如下示例xml 复制代码 代码如下: <?xml version="1.0" encoding="utf-8" ?> <?xml-stylesheet type="text/xsl" href="pets-templates.xsl"?> <pets> <pig color="blue" weight="100"> <price>100</price> <desc>this is a blue pig</desc> </pig> <cat color="red" weight="9"> <price>80</price> <desc>this is a red cat</desc> </cat> <dog color="green" weight="15"> <price>80</price> <desc>this is a green dog</desc> </dog> <cat color="green" weight="15"> <price>80</price> <desc>this is a green cat</desc> </cat>
<dog color="blue" weight="10"> <price>100</price> <desc>this is a blue dog</desc> </dog> <dog color="red" weight="9"> <price>80</price> <desc>this is a red dog</desc> </dog> </pets>
3) xsl:if 元素条件显示节点(类似编程语言中的if语句)注意小于号大于号要分别用<和>替代 复制代码 代码如下: <xsl:if test=”@weight < 10”> <i>its weight is less than 10 km</i> </xsl:if>
4) xsl:choose 多分支条件显示 (类似编程语言中的switch语句) 复制代码 代码如下: <xsl:choose > <xsl:when test=”name() = ‘pig'”> <i>this is a pig</i> </xsl:when> <xsl:otherwise> <i>this is not a pig</i> </xsl:otherwise> </xsl:choose>
<xsl:if test="@weight < 10"> <p> <i>its weight is less than 10 km</i> </p> </xsl:if> </li> </xsl:for-each> </xsl:template>
</xsl:stylesheet>
在c#.net中使用XslCompiledTransform转换xml文档,XslTransform也可以使用,但是这个类已经被微软标记为过时,最好不要再用了,如下代码示例: 复制代码 代码如下: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Xml;
namespace UseXslt { class Program { static void Main(string[] args) { //声明XslTransform类实例 System.Xml.Xsl.XslCompiledTransform trans = new System.Xml.Xsl.XslCompiledTransform();