Load, modify, and write an XML document in Groovy Load, modify, and write an XML document in Groovy xml xml

Load, modify, and write an XML document in Groovy


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>*/


If you want to use the XmlSlurper:

//Open filedef xml = new XmlSlurper().parse('/tmp/file.xml')//Edit File e.g. append an element called foo with attribute barxml.appendNode {   foo(bar: "bar value")}//Save Filedef writer = new FileWriter('/tmp/file.xml')//Option 1: Write XML all on one linedef builder = new StreamingMarkupBuilder()writer << builder.bind {  mkp.yield xml}//Option 2: Pretty print XMLXmlUtil.serialize(xml, writer)

Note:XmlUtil can also be used with the XmlParser as used in @John Wagenleitner's example.

References:


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.textFile.withWriter(Closure closure) 

See here for a complete list of these methods/properties.