XSLT排序问题 [英] XSLT sorting issue
问题描述
我有一个像这样的xml
I have an xml like:
<PersonList>
<Person>
<Name>Smith</Name>
<Role>5</Role>
</Person>
<Person>
<Name>Star</Name>
<Role>3</Role>
</Person>
<Person>
<Name>Wars</Name>
<Role>1</Role>
</Person>
</PersonList>
在xslt中,我想以一种方式进行排序,如果有角色1,则它应该是列表中的第一个人. 其余人员应按姓名按字母顺序排序.
In xslt I want to sort in such a way that if there is a Role 1 this should be the first Person in the list. The rest of the Persons should be sorted alphabetically by Name.
谢谢.
推荐答案
尝试一下:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/PersonList">
<xsl:copy>
<xsl:apply-templates select="Person">
<xsl:sort select="number(Role=1)" data-type="number" order="descending"/>
<xsl:sort select="Name" data-type="text" order="ascending"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
或者,如果您愿意:
...
<xsl:template match="/PersonList">
<xsl:copy>
<xsl:apply-templates select="Person[Role=1]"/>
<xsl:apply-templates select="Person[not(Role=1)]">
<xsl:sort select="Name" data-type="text" order="ascending"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
...
其他说明:
表达式Role=1
返回布尔结果.但是,XSLT 1.0的xsl:sort
指令只能按文本或数字排序.因此,结果必须先转换为字符串或数字,然后才能用于排序.
Additional Explanation:
The expression Role=1
returns a Boolean result. However, XSLT 1.0's xsl:sort
instruction can only sort by text or by number. Therefore the result must be converted to either a string or a number, before it can be used for sorting.
我更喜欢将Boolean转换为数字,因为这样在阅读代码时易于理解预期的顺序.
I prefer to convert the Boolean to a number, because then the intended order is easier to understand when reading the code.
出于相同的原因,即使它们分别是文本"和升序"的默认值,我也希望明确声明data-type
和order
.
For the same reason, I prefer to state the data-type
and order
explicitly, even when they are the default values of "text" and "ascending" respectively.
无论如何,如果希望按文本排序,则所需的过程在复杂性方面 1 相同:
In any case, if one prefers to sort as text, the required process is the same in terms of complexity1:
<xsl:sort select="not(Role=1)"/>
只是以下内容的简写:
<xsl:sort select="string(not(Role=1))" data-type="text" order="ascending"/>
与以下内容相同:
<xsl:sort select="string(Role=1)" data-type="text" order="descending"/>
这三个之间的唯一区别在于代码的可读性.
The only difference between these three is in code readability.
(1)有人可能会说数字排序比按字母排序更有效,但我不知道这一事实,所以我不会.
注意:
这些差异很小,很大程度上取决于个人喜好.
Note:
These differences are minor and largely a matter of personal preference.
这篇关于XSLT排序问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!