当我尝试将xml文件转换为另一个文件时遇到了问题。它需要按城市名称排序。但我的排序功能不起作用!!
这是我的cities.xml
<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="cities.xsl"?>
<cities>
<city id="c01">
<name>Shanghai</name>
<population>1111000</population>
<altitude>450</altitude>
</city>
<city id="c02">
<name>Wenzhou</name>
<population>277200</population>
<altitude>220</altitude>
</city>
<city id="c03">
<name>Beijing</name>
<population>2222000</population>
<altitude>662</altitude>
</city>
</cities>
这是cities.xslt
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="cities">
<cities>
<xsl:apply-templates>
<xsl:sort select="city/name"/> //doesn't work!!!
</xsl:apply-templates>
</cities>
</xsl:template>
<xsl:template match="city">
<city>
<xsl:attribute name="name">
<xsl:value-of select="name" />
</xsl:attribute>
<inhabitants>
<xsl:apply-templates select="population"/>
</inhabitants>
</city>
</xsl:template>
<xsl:template match="population">
<xsl:value-of select="."/>
</xsl:template>
</xsl:stylesheet>
但是当我用
更改行时<xsl:sort select="name"/> //it works!!!
谁能告诉我为什么?请!!
答案 0 :(得分:1)
它不起作用,因为您尝试对city/name
元素进行排序的表达式city
是根据city
的上下文进行评估的 - 并从该上下文中进行评估什么都不返回,因为city
不是自己的孩子。
请参阅:
http://www.w3.org/TR/xslt/#sorting
这个例子与我的区别是什么?
在给定示例中(简化):
<xsl:template match="employees">
<xsl:apply-templates select="employee">
<xsl:sort select="name/family"/>
</xsl:apply-templates>
</xsl:template>
employees
employee
name/family
排序键值的组合路径:employees/employee/name/family
在您的示例中(为了清晰起见略微调整):
<xsl:template match="cities">
<xsl:apply-templates select="city">
<xsl:sort select="city/name"/>
</xsl:apply-templates>
</xsl:template>
cities
city
city/name
排序键值的组合路径:cities/city/city/name
您是否看到此路径存在问题?