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.
The most commonly used approach for creating XML with Groovy is to use a builder, i.e. one of: groovy. xml.
XML ParsingThe Groovy XmlParser class employs a simple model for parsing an XML document into a tree of Node instances. Each Node has the name of the XML element, the attributes of the element, and references to any child Nodes. This model is sufficient for most simple XML processing.
Represents an arbitrary tree node which can be used for structured metadata or any arbitrary XML-like tree. A node can have a name, a value and an optional Map of attributes.
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 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:
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