Modifying XML content

In this recipe, we will learn how to update and delete nodes of a parsed XML document using the XmlParser.

Getting ready

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)

How to do it...

The simplest way to change the value of a node is to reference it using the position of the node itself.

  1. For instance, if we want to change the model ...

Get Groovy 2 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.