Groovy: cloning nodes in an XML document

It’s pretty easy to clone nodes in a XML document using Groovy once XmlParser is used instead of XmlSlurper:

import groovy.xml.XmlUtil

def original = """
   <book id="sample">

def catalog = new XmlParser().parseText( original )

def sampleBook = { it.@id == "sample" }


3.times {
  def c = sampleBook.clone()
  c.@id = "$it"[0].value = "Author $it"
  c.title[0].value = "Title $it"


println XmlUtil.serialize(catalog)

The result is:

<?xml version="1.0" encoding="UTF-8"?><catalog>
  <book id="0">
    <author>Author 0</author>
    <title>Title 0</title>
  <book id="1">
    <author>Author 1</author>
    <title>Title 1</title>
  <book id="2">
    <author>Author 2</author>
    <title>Title 2</title>


This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s