XSLT 使用字典对元素进行排序
XSLT Sort elements using dictionary
我有一个 XML 列表,其中包含国家代码:
<Countries>
<Country Code="DE" />
<Country Code="FR" />
</Countries>
我将 XSLT 应用于此 XML 以转换为 HTML,并且我希望元素按国家名称而不是代码的字母顺序排序。
所以我定义了 CountryCodeDictionaryEN 变量,它是国家代码和名称的字典。它在 <xsl:value-of />
中工作正常,但在 <xsl:sort />
中不工作
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt">
<xsl:variable name="CountryCodeDictionaryEN">
<item key="Germany"
value="DE" />
<item key="France"
value="FR" />
... all other countries ...
</xsl:variable>
<xsl:template match="/">
<table>
<xsl:for-each select="Countries/Country">
<xsl:sort select="msxsl:node-set($CountryCodeDictionaryEN)/item[@value = @Code]/@key"/>
<tr>
<td>
<xsl:variable name="Code" select="@Code"/>
<xsl:value-of select="msxsl:node-set($CountryCodeDictionaryEN)/item[@value = $Code]/@key"/>
</td>
</tr>
</table>
</xsl:template>
</xsl:stylesheet>
item[@value = @Code]
将 item
的 value
属性与同一项目 的 Code
属性 进行比较。由于 item
元素没有 Code
属性,因此 select
表达式将始终导致空节点集,因此每个节点都将获得相同的(空字符串)排序键。并且由于 xsl:sort
是稳定的(具有相同排序键值的项目保留其原始相对顺序)整体效果是没有排序。
您需要使用谓词的current()
到"break out"并引用被sort
编辑的节点:
<xsl:sort select="msxsl:node-set($CountryCodeDictionaryEN)
/item[@value = current()/@Code]/@key"/>
这会将 item
的 value
与 Country
的 Code
进行比较。
我有一个 XML 列表,其中包含国家代码:
<Countries>
<Country Code="DE" />
<Country Code="FR" />
</Countries>
我将 XSLT 应用于此 XML 以转换为 HTML,并且我希望元素按国家名称而不是代码的字母顺序排序。
所以我定义了 CountryCodeDictionaryEN 变量,它是国家代码和名称的字典。它在 <xsl:value-of />
中工作正常,但在 <xsl:sort />
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt">
<xsl:variable name="CountryCodeDictionaryEN">
<item key="Germany"
value="DE" />
<item key="France"
value="FR" />
... all other countries ...
</xsl:variable>
<xsl:template match="/">
<table>
<xsl:for-each select="Countries/Country">
<xsl:sort select="msxsl:node-set($CountryCodeDictionaryEN)/item[@value = @Code]/@key"/>
<tr>
<td>
<xsl:variable name="Code" select="@Code"/>
<xsl:value-of select="msxsl:node-set($CountryCodeDictionaryEN)/item[@value = $Code]/@key"/>
</td>
</tr>
</table>
</xsl:template>
</xsl:stylesheet>
item[@value = @Code]
将 item
的 value
属性与同一项目 的 Code
属性 进行比较。由于 item
元素没有 Code
属性,因此 select
表达式将始终导致空节点集,因此每个节点都将获得相同的(空字符串)排序键。并且由于 xsl:sort
是稳定的(具有相同排序键值的项目保留其原始相对顺序)整体效果是没有排序。
您需要使用谓词的current()
到"break out"并引用被sort
编辑的节点:
<xsl:sort select="msxsl:node-set($CountryCodeDictionaryEN)
/item[@value = current()/@Code]/@key"/>
这会将 item
的 value
与 Country
的 Code
进行比较。