Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort XML tags into alphabetical order

Tags:

xml

anyone know of a way that I can load an XML file into and sort it and then save the file?

I have a xml file with a bunch of settings.. and now it is getting hard to manage because they are not in any natural sort order...

e.g.

<edit_screen_a>
<settings_font_size>
<edit_screen_b>
<display_screen>
<settings_font_name>

to sort to:

<display_screen>
<edit_screen_a>
<edit_screen_b>
<settings_font_name>
<settings_font_size>
like image 712
ycomp Avatar asked Feb 06 '12 14:02

ycomp


People also ask

How do you sort tags in XML?

The xsl:sort does sort the file elements before applying the templates with the sort key ref and the implied default order ascending . Now pass both files (the XML and the XSLT stylesheet) to an XSLT processor of your choice and you'll get the desired (sorted) output.

Can you sort an XML file?

The Recursive XML sort option will sort all nodes recursively (e.g., to remove ordering prior to diffing). First, it sorts nodes by type: text nodes come first, then processing instructions, then elements. Element attributes are sorted first by name, then by value.

How do I sort XML in Notepad ++?

Notepad++ has a sort feature, but can't directly sort the quoted format. So, as a workaround, the idea is to reformat that text in order to be able to apply the kind of sort provided by Notepad++. This is doable via a couple of search and replace in regex mode.


1 Answers

You could use XSLT and run it from the command line. (I'd recommend Saxon, but Xalan would be ok.)

Here's an example...

XML Input

<doc>
  <edit_screen_a/>
  <settings_font_size/>
  <edit_screen_b/>
  <display_screen/>
  <settings_font_name/>
</doc>

XSLT 1.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="doc">
    <doc>
      <xsl:apply-templates>
        <xsl:sort select="name()"/>
      </xsl:apply-templates>      
    </doc>
  </xsl:template>

</xsl:stylesheet>

XML Output

<doc>
   <display_screen/>
   <edit_screen_a/>
   <edit_screen_b/>
   <settings_font_name/>
   <settings_font_size/>
</doc>
like image 68
Daniel Haley Avatar answered Nov 06 '22 14:11

Daniel Haley