key(string,object)函数用于在一个索引中依照key值搜索对应的节点。参数string用于指定索引对象的名字,参数object用于指定查找时的key值。
语法:key(string,object)
参数:string字符串,必需;object字符串,必需
返回值:节点集合
示例:
xml:
-
<?xml version="1.0" encoding="UTF-8"?>
-
<customers>
-
<customer>
-
<name>Alex</name>
-
<age>25</age>
-
<country>China</country>
-
</customer>
-
<customer>
-
<name>Kin</name>
-
<age>27</age>
-
<country>England</country>
-
</customer>
-
<customer>
-
<name>Kevin</name>
-
<age>28</age>
-
<country>China</country>
-
</customer>
-
<customer>
-
<name>Bob</name>
-
<age>25</age>
-
<country>England</country>
-
</customer>
-
<customer> <name>John</name> <age>25</age> <country>America</country> </customer> <customer> <name>Joe</name> <age>32</age> <country>England</country> </customer> <customer> <name>Mark</name> <age>25</age> <country>America</country> </customer> </customers>
xslt:
-
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" version="1.0" encoding="gb2312" indent="yes"/> <xsl:key match="customer" name="customerKey" use="country"/> <xsl:template match="customers"> <xsl:copy> <xsl:for-each select="customer[generate-id(.)=generate-id(key('customerKey',country))]"> <xsl:sort select="country"/> <xsl:for-each select="../customer[country=current()/country]"> <xsl:sort select="name"/> <xsl:copy-of select="."/> </xsl:for-each> </xsl:for-each> </xsl:copy> </xsl:template> </xsl:stylesheet>
结果:
-
<?xml version="1.0" encoding="gb2312"?> <customers> <customer> <name>John</name> <age>25</age> <country>America</country> </customer> <customer> <name>Mark</name> <age>25</age> <country>America</country> </customer> <customer> <name>Alex</name> <age>25</age> <country>China</country> </customer> <customer> <name>Kevin</name> <age>28</age> <country>China</country> </customer> <customer> <name>Bob</name> <age>25</age> <country>England</country> </customer> <customer> <name>Joe</name> <age>32</age> <country>England</country> </customer> <customer> <name>Kin</name> <age>27</age> <country>England</country> </customer> </customers>