I have an XML document that I want to load from a file, modify a few specific elements, and then write back to disk.
I can't find any examples of how to do this in Groovy.
I have an XML document that I want to load from a file, modify a few specific elements, and then write back to disk.
I can't find any examples of how to do this 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.
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>
*/