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://archive.cnblogs.com/a/404070/