在中文网站到看到了不少关于
XSLT
的例子,可是大部分都属于入门性质的。下面给出一个
XSLT
的例子,说明
XSLT
的一些典型的用法。
XSLT1.0
规范定义了
document()
函数,提供了初步的处理多个
xml
输入文件的功能。我们用这个功能来实现新旧
xml
文件的比较。
比如,我们有一个
xml
格式产品列表,列出一些关于
XSLT
处理的(
Open Source
)软件。
每隔一段时间,我们就更新一次产品列表。
下面的
Product.1.xml
是第一个产品列表。
product.1.xml
<?xml version="1.0" ?>
<product-root>
<!-- no histroy yet -->
<product-history/>
<product>
<product-id>001</product-id>
<product-name>Apache Xalan xslt</product-name>
<url>http://xml.apache.org/xalan-j/</url>
</product>
<product>
<product-id>002</product-id>
<product-name>saxon xslt</product-name>
<url>http://saxon.sourceforge.net/</url>
</product>
</product-root>
过了一段时间,产品列表更新为
Product.2.xml
。其中的
product-history
元素纪录以前的产品列表——
Product.1.xml
。
product.2.xml
<?xml version="1.0" ?>
<product-root>
<!-- refer to last product list -->
<product-history>product.1.xml</product-history>
<product>
<product-id>001</product-id>
<product-name>Apache Xalan xslt</product-name>
<url>http://xml.apache.org/xalan-j/</url>
</product>
<product>
<product-id>002</product-id>
<product-name>saxon xslt</product-name>
<url>http://saxon.sourceforge.net/</url>
</product>
<product>
<product-id>003</product-id>
<product-name>XT xslt</product-name>
<url>http://www.4xt.org/</url>
</product>
<product>
<product-id>004</product-id>
<product-name>oasis xslt</product-name>
<url>http://www.oasis-open.org/</url>
</product>
</product-root>
我们用下面的
xsl
文件处理
product.2.xml
,查找新增加的
product
。
product.diff.xsl
<?xml version="1.0"?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="product-root">
<difference>
<!-- get all history product-->
<xsl:variable name="history" select="document(product-history)//product" />
<!-- copy the product which is not in product history -->
<xsl:copy-of select="product[not(product-id=$history/product-id)]"/>
</difference>
</xsl:template>
</xsl:transform>
这个
XSL
文件虽然短小,却包括了
XSLT
很重要的一些特性和
XPath
的很典型的用法。因为
product-history
的内容是
product.1.xml
,所以
document(product-history)
取得上次产品列表
product.1.xml
的根元素。
document(product-history)//product
取得
product.1.xml
的根元素下面所有的
product
元素。我们也可以写成
document(product-history)/product-root/product
,这种写法更加确定,指定只选取
product-root
元素下面的
product
。
注意,
product[not(product-id=$history/product-id)]
表示“
product-id
和
history product-id
都不相同
的
product
”;
product[product-id!=$history/product-id]
表示“
product-id
和
history product-id
至少有一个不相同
的
product
”。
处理后的
xml
结果如下。
<?xml version="1.0" encoding="UTF-8"?>
<difference>
<product>
<product-id>003</product-id>
<product-name>XT xslt</product-name>
<url>http://www.4xt.org/</url>
</product>
<product>
<product-id>004</product-id>
<product-name>oasis xslt</product-name>
<url>http://www.oasis-open.org/</url>
</product>
</difference>
关于如何运行这个例子或其它的
XSLT
例子。首先,您需要一个
XSLT
转换工具。哪里获得
XSLT
转换工具呢?参见上面的产品列表
product.2.xml
,里面就包括了很好的
XSLT
转换工具。访问里面的
url
。
:-)
http://www.tongyi.net/develop/Java/1010664.html