使用:
/*/*/*/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