使用:
/*/*/*/product[price > 5]/title
|
/*/*/*/product/price[. > 5]
这将选择的工会:
有一个product
父时为数字处理,其price
孩子的字符串值大于5的所有title
元素这是XML文档顶层元素的重孙。
所有price
元件,其字符串值当作为处理过的数大于5,且父是product
在XML文档的顶部元件的曾孙。在按文档顺序的节点集(典型地),这意味着一个title
及其相应price
在任何节点的集合是由相应的XPath API产生是彼此相邻设置
选择的元素。
在XSLT人会用一个很简单的改造是这样的:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:strip-space elements="*"/>
<xsl:template match="product[price > 5]">
Name: <xsl:value-of select="title"/>
<xsl:text>, price </xsl:text>
<xsl:value-of select="price"/>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
时所提供的XML文档应用:
<food>
<fruit>
<apple>
<product>
<title>Apple 1</title>
<price>7</price>
</product>
<product>
<title>Apple 2</title>
<price>4</price>
</product>
</apple>
<grapes>
<product>
<title>Red grapes </title>
<price>4</price>
</product>
<product>
<title>Green grapes</title>
<price>6</price>
</product>
</grapes>
</fruit>
<drink>
<water>
<product>
<title>Water 1</title>
<price>1</price>
</product>
<product>
<title>Water 2</title>
<price>6</price>
</product>
</water>
<soda>
<product>
<title>Coca-Cola</title>
<price>10</price>
</product>
<product>
<title>Sprite</title>
<price>4</price>
</product>
</soda>
</drink>
</food>
想要的,正确的结果产生:
Name: Apple 1, price 7
Name: Green grapes, price 6
Name: Water 2, price 6
Name: Coca-Cola, price 10
将价格限制指定为外部传递给变换的全局参数甚至更好。
在这种情况下,一个XSLT 2。0变换是简单一点:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:strip-space elements="*"/>
<xsl:param name="pLimit" select="5"/>
<xsl:template match="product[price > $pLimit]">
Name: <xsl:value-of select="title"/>
<xsl:text>, price </xsl:text>
<xsl:value-of select="price"/>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
甲相应XSLT 1.0变换是:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:strip-space elements="*"/>
<xsl:param name="pLimit" select="5"/>
<xsl:template match="product">
<xsl:if test="price > $pLimit">
Name: <xsl:value-of select="title"/>
<xsl:text>, price </xsl:text>
<xsl:value-of select="price"/>
</xsl:if>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
错失 food>。 当然,它是在XML结构 – IVar