I would like to be able to sort some elements first by the name of some of their child elements, and then by an attribute.
Here is an example. I have simplified it from my actual requirement so hopefully that doesn't cause more confusion that it solves. The real requirement has a number of other elements as siblings to the 'Animals
with their own sorting requirements but this fragment in particular is giving me grief.
Before Transformation
<Animals>
<Animal Value="20160.17">
<Identifier id="1" />
<Pig><!-- more elements inside here--></Pig>
</Animal>
<Animal Value="5000.40">
<Identifier id="2" />
<Cow><!-- more elements inside here--></Cow>
</Animal>
<Animal Value="63.44">
<Identifier id="3" />
<Pig><!-- more elements inside here--></Pig>
</Animal>
<Animal Value="4800.40">
<Identifier id="4" />
<Cow><!-- more elements inside here--></Cow>
</Animal>
</Animals>
Desired Transformation
I would like each Animal
element sorted so that all Animal
s with a Cow
child come first, followed by all Animal
s with a Pig
child. Within each of those categories, they should be sorted numerically by the Animal
's Value
attribute.
After Transformation
<Animals>
<Animal Value="4800.40">
<Identifier id="4" />
<Cow><!-- more elements inside here--></Cow>
</Animal>
<Animal Value="5000.40">
<Identifier id="2" />
<Cow><!-- more elements inside here--></Cow>
</Animal>
<Animal Value="63.44">
<Identifier id="3" />
<Pig><!-- more elements inside here--></Pig>
</Animal>
<Animal Value="20160.17">
<Identifier id="1" />
<Pig><!-- more elements inside here--></Pig>
</Animal>
</Animals>
Attempt
I'm pretty new at XSL and my best attempt so far doesn't seem to take the Cow/Pig elements into account. It only sorts by the Value
attribute:
<xsl:template match="Animals">
<xsl:copy>
<xsl:apply-templates select="Animal">
<xsl:sort select="name(*) = 'Cow'" />
<xsl:sort select="name(*) = 'Pig'" />
<xsl:sort select="@Value" data-type="number" />
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
question from:
https://stackoverflow.com/questions/65838432/how-to-use-xsl-to-sort-elements-by-child-element-names 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…