Load, modify, and write an XML document in Groovy
There's a pretty exhaustive set of examples for reading/writing XML using Groovy here. Regarding the loading/saving the data to/from a file, the various methods/properties that Groovy adds to java.io.File
, should provide the functionality you need. Examples include:
File.write(text)
File.text
File.withWriter(Closure closure)
See here for a complete list of these methods/properties.
If you want to use the XmlSlurper:
//Open file
def xml = new XmlSlurper().parse('/tmp/file.xml')
//Edit File e.g. append an element called foo with attribute bar
xml.appendNode {
foo(bar: "bar value")
}
//Save File
def writer = new FileWriter('/tmp/file.xml')
//Option 1: Write XML all on one line
def builder = new StreamingMarkupBuilder()
writer << builder.bind {
mkp.yield xml
}
//Option 2: Pretty print XML
XmlUtil.serialize(xml, writer)
Note:
XmlUtil
can also be used with the XmlParser
as used in @John Wagenleitner's example.
References:
- Option 1
- Option 2
You can just modify the node's value property to modify the values of elements.
/* input:
<root>
<foo>
<bar id="test">
test
</bar>
<baz id="test">
test
</baz>
</foo>
</root>
*/
def xmlFile = "/tmp/test.xml"
def xml = new XmlParser().parse(xmlFile)
xml.foo[0].each {
it.@id = "test2"
it.value = "test2"
}
new XmlNodePrinter(new PrintWriter(new FileWriter(xmlFile))).print(xml)
/* output:
<root>
<foo>
<bar id="test2">
test2
</bar>
<baz id="test2">
test2
</baz>
</foo>
</root>
*/