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 = """
<catalog>
   <book id="sample">
      <author>sample</author>
      <title>sample</title>
   </book>
</catalog>
"""

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

def sampleBook = catalog.book.find { it.@id == "sample" }

catalog.remove(sampleBook)

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

  catalog.append(c)
}

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>
  <book id="1">
    <author>Author 1</author>
    <title>Title 1</title>
  </book>
  <book id="2">
    <author>Author 2</author>
    <title>Title 2</title>
  </book>
</catalog>

 

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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