In this recipe, we will learn how to update and delete nodes of a parsed XML document using the XmlParser
.
Let's start by parsing the following XML with the XmlParser
(see the Reading XML using XmlParser recipe):
def carXml = ''' <?xml version="1.0" ?> <cool-cars> <car manufacturer="Ferrari"> <model>430 Scuderia</model> </car> <car manufacturer="Porsche"> <model>911</model> </car> <car manufacturer="Lotus"> <model>Elan</model> </car> <car manufacturer="Pagani"> <model>Huayra</model> </car> </cool-cars> ''' def coolCars = new XmlParser().parseText(carXml)
The simplest way to change the value of a node is to reference it using the position of the node itself.
coolCars.car[2].model[0].value = 'Elise'
coolCars.find { it.@manufacturer == 'Ferrari' }.model[0].value = 'Testarossa'
Instead of referencing the node by its position, we use the find
method to reference the attribute of the node.
coolCars.car[1].@manufacturer = 'Ford'
coolCars.remove(coolCars.car[3]) coolCars.remove(coolCars.car[1])
or even better:
coolCars.findAll { [email protected]('P') } .each { coolCars.remove(it) }
This previous example deletes every car's manufacturer, whose name starts with the letter P.
new XmlNodePrinter().print(coolCars)
<cool-cars> <car manufacturer="Ferrari"> <model> Testarossa </model> </car> <car manufacturer="Lotus"> <model> Elise </model> </car> </cool-cars>
Thanks to Groovy's dynamic typing and metaprogramming capabilities, we can access the members of our document directly by name, as shown in several other recipes from this chapter: Reading XML using XmlSlurper, Searching in XML with GPath, and Constructing XML content.
In most cases, we operate directly on the groovy.util.Node
classes or collections of nodes. The full power of the Groovy Collection API can be applied easily to navigate and modify the document tree.
In the previous code, we also made use of the .@
operator, which gives access to an attribute of an XML element.
In the last step, we print out the resulting in-memory node tree to the standard output with the help of the XmlNodePrinter
class. This class pretty prints a groovy.util.Node
including all children in XML format.
18.119.106.135