I need to print XML that I manipulated using groovy and maintain the attribute order. I don’t care if it’s using XmlParser/XmlNodePrinter or XmlSlurper/StreamingMarkupBuilder. My current code is as follows:
File file = new File('input.xml')
def root = new XmlSlurper().parse(file)
def admins = root.user.findAll {it.@role.text().equals("admin")}
admins.each { admin ->
admin.permission.findAll { it.@interface.text().equals("RoleManagement")
}.each {
it.@implementation = "AdminRoleManagement"
}
}
def smb = new StreamingMarkupBuilder().bind { mkp.yield root }
new File('output.xml').text = groovy.xml.XmlUtil.serialize(smb)
Here’s the XML that gets fed into the program
<users>
<user username="test1234" role="admin">
<permission interface="com.test.RoleManagement" implementation="com.test.AdminRoleManagement"/>
<permission interface="com.test.UserAdministration" implementation="com.test.UserAdministrationImpl"/>
</user>
</users>
After I print out the modified file, though, the interface and implementation attributes are reversed.
I already know what you’re thinking: xml attribute order does not matter. Well, my requirement from my boss is to preserve the attribute order b/c it has been that way for ages. I was actually supposed to write this parser using Java/DOM4J and I was trying to show my team something new. Any help would be appreciated. Thanks!
I don’t think this is possible without writing your own code to output the XML.
The SAX parser has no concept of attribute ordering (AFAIK), and so the order will be lost before
XmlSlurpereven sees the data… I found a thread on the groovy-user list which has a discussion of this, but it doesn’t seem to come up with any solutions…I think it’s possible with
XmlParser, as that seems to maintain order:That prints:
Which at first glance seems right?