Groovy - XmlNodePrinter prints empty file
I am trying to print formatted xml to a file, but my XmlNodePrinter just prints an empty file. I think the xml object I am passing is populated correctly. I can print it using StreamingMarkupBuilder, but it is formatted on one line. I'm not sure why I can't use the XmlNodePrinter. Here is the relevant part of my code.
The purpose of the code is to modify the xml configuration file. I have to do search / replace at a specific resolution.
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.@type.text().equals("RoleManagement")
}.each {
it.@type = "AdminRoleManagement"
}
}
String filename = "output.xml"
new XmlNodePrinter(new PrintWriter(filename)).print(root)
thank
source to share
I believe it XmlNodePrinter
requires Node
, notGPathResult
XmlSlurper.parse
returns GPathResult
So the obvious solution is to use XmlParser
insteadXmlSlurper
Or you can use StreamingMarkupBuilder
and do:
def smb = new StreamingMarkupBuilder().bind { mkp.yield root }
new File( 'output.xml' ).text = groovy.xml.XmlUtil.serialize( smb )
source to share