If the accepted answer is giving you problems, consider this:
sort.xslt
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- for well formatted output -->
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="*">
<!-- copy this node (but this does not copy the attributes ...) -->
<xsl:copy>
<!-- so, copy the attributes as well -->
<xsl:copy-of select="@*"/>
<!-- recurse on sorted (by tag name) list of child nodes -->
<xsl:apply-templates>
<xsl:sort select="name()"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
(Reference documentation on XSLT including the various operations used above may be found on MDN)
Compared to https://stackoverflow.com/a/9165464/5412249
- does not assume any particular root node
- preserves the attributes as well
- uses a single template (and IMHO more easier to understand)
To actually apply this, on a Mac (and presumably on linux systems as well), you may use xsltproc
xsltproc sort.xslt test.xml
where, test.xml
is any arbitrary xml file