Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load, modify, and write an XML document in Groovy

Tags:

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.

like image 770
Mike Sickler Avatar asked Feb 11 '10 15:02

Mike Sickler


People also ask

Which of the following method is used to write an XML document in groovy?

The most commonly used approach for creating XML with Groovy is to use a builder, i.e. one of: groovy. xml.

How to parse XML in Groovy?

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.

What is node in groovy script?

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.


2 Answers

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> */ 
like image 104
John Wagenleitner Avatar answered Sep 22 '22 06:09

John Wagenleitner


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
like image 33
Heinrich Filter Avatar answered Sep 20 '22 06:09

Heinrich Filter