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>
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.
Thanks in advance.
A simpler and shorter solution -- no numeric sorting is really necessary:
Explanation:
When Boolean values are sorted,
false()
comes beforetrue()
.Multi-key sorting
Try it this way:
XSLT 1.0
Or, if you prefer:
Additional Explanation:
The expression
Role=1
returns a Boolean result. However, XSLT 1.0'sxsl: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.I prefer to convert the Boolean to a number, because then the intended order is easier to understand when reading the code.
For the same reason, I prefer to state the
data-type
andorder
explicitly, even when they are the default values of "text" and "ascending" respectively.In any case, if one prefers to sort as text, the required process is the same in terms of complexity1:
is just a short-hand version of:
which is the same thing as:
The only difference between these three is in code readability.
(1) One could argue that sorting numerically will be more efficient than sorting alphabetically, but I don't know that for a fact, so I won't.
Note:
These differences are minor and largely a matter of personal preference.