This is my Groovy code:
// ...
def xml = new XmlParser().parse(fileName)
xml.each { e ->
// some changes are being made to XML
xml.append("test", "test me")
}
def writer = new FileWriter(newFileName)
new XmlNodePrinter(new PrintWriter(writer)).print(xml)
The code works, but the output XML has a lot of unnecessary white spaces. Looks like I'm doing something wrong with writing to file.
ps. Thanks to Tim, this is how it should work (the last line of the example above shall be replaced with these three lines):
def printer = new XmlNodePrinter(new PrintWriter(writer))
printer.preserveWhitespace = true
printer.print(xml)
What happens if you replace:
def writer = new FileWriter(newFileName)
new XmlNodePrinter(new PrintWriter(writer)).print(xml)
with:
new File( newFilename ).withWriter { out ->
printer = new XmlNodePrinter( out )
printer.preserveWhitespace = true
printer.print( xml )
}
-- edit --
As pointed out, it feels like it should be preserveWhitespace = false
, however if you try the following test code:
def x = """<langs type="current">
<language>Java</language>
<language>Groovy</language>
<language>JavaScript</language>
</langs>"""
def xml = new XmlParser().parseText( x )
xml.appendNode 'language', 'Ruby'
def printIt = { node, pw ->
println "With preserveWhitespace=$pw:"
def s = new StringWriter()
printer = new XmlNodePrinter( new PrintWriter( s ) )
printer.preserveWhitespace = pw
printer.print( xml )
println s
}
printIt xml, true
printIt xml, false
You get the output:
With preserveWhitespace=true:
<langs type="current">
<language>Java</language>
<language>Groovy</language>
<language>JavaScript</language>
<language>Ruby</language>
</langs>
With preserveWhitespace=false:
<langs type="current">
<language>
Java
</language>
<language>
Groovy
</language>
<language>
JavaScript
</language>
<language>
Ruby
</language>
</langs>
I ended up with this blurb:
new File(myFilename).withWriter {
def printer = new XmlNodePrinter(new PrintWriter(it))
printer.preserveWhitespace = true
printer.print(myXmlNode)
}
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