首页 > 解决方案 > XSLT 对变量中的数据进行排序并将它们保存到另一个变量

问题描述

我有个问题。我有以下 XML

<countryList> 
   <country>
      <name>Afghanistan</name>
      <population>29117000</population>
      <area>654329</area>
   </country>
   <country>
      <name>Albania</name>
      <population>3195000</population>
      <area>28748</area>
   </country>
   <country>
      <name>Algeria</name>
      <population>35423000</population>
      <area>2381741</area>
   </country>
   <country>
      <name>Andorra</name>
      <population>84082</population>
      <area>468</area>
   </country>
</countryList>

我有一个问题。我需要做的就是划分人口/区域并对每个国家的这些划分进行排序。但是,我试过这个

<xsl:variable name="Podiel">
        <xsl:value-of select="../population div ../area"/>
    </xsl:variable>

    <xsl:variable name="PodielPodiel">
        <xsl:for-each select="$Podiel">
            <xsl:sort select="." data-type="number" order="descending"/>
        </xsl:for-each>
    </xsl:variable>

但我仍然收到错误

The 'select' expression does not evaluate to a node set.
no result for data1.xml

有什么帮助吗?我只想知道所有部门的最大值。谢谢。

标签: xslt-1.0

解决方案


不确定问题是否已解决,但是要node-set在 XSLT 1.0 中使用,必须使用扩展函数。有关它在 XSLT 1.0 中的使用的更多详细信息,请参阅节点集扩展

如果country输入 XML 中的列表需要根据 的值进行排序,则可以在 中使用population div area该函数。不需要声明变量并计算附加值然后访问变量。number()<xsl:sort>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" > 
    <xsl:output method="xml" />
    <xsl:strip-space elements="*" />

    <!-- identity transform -->
    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="countryList">
        <xsl:copy>
            <xsl:apply-templates select="country">
                <xsl:sort select="number(population div area)" data-type="number" order="descending" />
            </xsl:apply-templates>
        </xsl:copy>     
    </xsl:template>
</xsl:stylesheet>

输出

<countryList>
    <country>
        <name>Andorra</name>
        <population>84082</population>
        <area>468</area>
    </country>
    <country>
        <name>Albania</name>
        <population>3195000</population>
        <area>28748</area>
    </country>
    <country>
        <name>Afghanistan</name>
        <population>29117000</population>
        <area>654329</area>
    </country>
    <country>
        <name>Algeria</name>
        <population>35423000</population>
        <area>2381741</area>
    </country>
</countryList>

推荐阅读