XSLT为什么sort函数不能用于更具体的路径?

时间:2015-02-06 21:49:40

标签: xml xslt

当我尝试将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!!!

谁能告诉我为什么?请!!

1 个答案:

答案 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

您是否看到此路径存在问题?