I have an input XML file which I need to copy 1:1 to the output, except for one subelement which contains subitems that need to be sorted.
<?xml version='1.0'?> <top> <elementA /> <elementB /> <contents> <contentitem> <id>3</id> <moretags1 /> <moretags2 /> </contentitem> <contentitem> <id>2</id> <moretags1 /> <moretags2 /> </contentitem> <contentitem> <id>1</id> <moretags1 /> <moretags2 /> </contentitem> </contents> </top>
I’d like an XSL Transformation that puts the ‘contentitem’ elements in order, sorted by their ‘id’ elements. All other tags, including nested ones, must be copied verbatim. I already tried with xsl:copy, but either I get double contents or something turns out missing.
Mark Gravell’s solution is almost correct — with a slight issue that creates two nested
<contents>elements. Note to all who provide answers: Do test your solutions!Here is a correct solution. This transformation:
when applied on the originally-provided XML document:
produces the wanted, correct result:
Do note the following:
The use of the identity rule to copy all nodes without change.
How the identity template is overriden with a specific template matching the
contentselementThe use of the
<xsl:sort>instruction to present the results of applying a template in a specific order, possibly different from the document order of the nodes, selected for processing.