Skip to content

Instantly share code, notes, and snippets.

@akunzai
Last active March 12, 2019 08:46
Show Gist options
  • Select an option

  • Save akunzai/978342fdf14f9e85746e99cb7a01ee46 to your computer and use it in GitHub Desktop.

Select an option

Save akunzai/978342fdf14f9e85746e99cb7a01ee46 to your computer and use it in GitHub Desktop.
XML properties sorter
if (args.length == 0) {
println("Usage: groovy sortxml.groovy messages.xml [key]")
println("read from STDIN: groovy sortxml.groovy - [key]")
System.exit(0)
}
def input = args[0] == '-'
? System.in
: new File(args[0]).newInputStream()
def key = args.size() > 1 ? args[1] : 'key'
def parser = new XmlParser()
parser.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false)
parser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false)
input.withStream { stream ->
def rootNode = parser.parse(stream)
rootNode.children().sort(true) {it.attribute(key)}
def printer = new XmlNodePrinter(preserveWhitespace:true)
printer.print(rootNode)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment