tags:

views:

375

answers:

3

Is there any tool that can (pretty-print) format XML file as well as sort both its elements and attributes?

A: 

Loading an XML file into the free XML Notepad 2007 and saving it (without any change) will "pretty print" format it.

Your other request appears to be specific, and you'll probably will need to whip up a bit of code for it. Essentially reading in the document, parsing its elements and attributes and after all are in, sorting and building an equivalent (but reordered) DOM.

mjv
But is there a tool that can at least sort attributes? I understand that element sorting can be schema-related, but attribute order is independent of any schema definition. So, I guess there should be some tool that allows that right away without additional coding.
Superfilin
+1  A: 

xslt can do both.

Dave Jarvis
I would be more intrested in a GUI tool ( or even a command line tool ) that does not require any additional coding.
Superfilin
A: 

I have found this post: http://www.biglist.com/lists/xsl-list/archives/200106/msg01225.html that uses the following XSLT to indent XML and also sort attributes:

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

  <xsl:output method="xml" indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="/">
    <xsl:apply-templates/>
  </xsl:template>

  <xsl:template match="*">
    <xsl:copy>
      <!-- Sort the attributes by name. -->
      <xsl:for-each select="@*">
        <xsl:sort select="name( . )"/>
        <xsl:copy/>
      </xsl:for-each>
      <xsl:apply-templates/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="text()|comment()|processing-instruction()">
    <xsl:copy/>
  </xsl:template>

</xsl:stylesheet>

I haven't tried it yet, but most likely I will stick to XSLT to do formatting for me.

Superfilin