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>
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With