2

I have some xml that I'm parsing with XmlSlurper and I want to add a new node and then reference that new node. This demonstrates what I'm trying to do. Any solutions to this besides 1. add node 2. serialize 3. parse again 4. reference new node ?

import groovy.xml.XmlUtil
def xml = new XmlSlurper().parseText("<foo/>") 
xml.appendNode({bar()});
//now try to append something to bar.  Probably doesn't work because it's a closure
xml.bar.appendNode({baz()})
//no baz inside bar
println XmlUtil.serialize(xml)

Thanks.

EDIT:

You have to use XMLParser to get this to work:

import groovy.xml.XmlUtil

//slurper - does NOT work
def xml = new XmlSlurper().parseText("<foo/>") 
xml.appendNode({bar()});
//now try to append something to bar
xml.bar.appendNode({baz()})
//no baz inside bar
println XmlUtil.serialize(xml)

//parser - works

xml = new XmlParser().parseText("<foo/>") 
xml.appendNode('bar');
//now try to append something to bar
xml.bar.first().appendNode('baz')
//no baz inside bar
println XmlUtil.serialize(xml)

The why is explained in the answer to this post:

Groovy XmlSlurper vs XmlParser

Community
  • 1
  • 1

1 Answers1

1

What is the problem in using as below?

import groovy.xml.XmlUtil

def xml = new XmlSlurper().parseText( "<foo/>" ) 

xml.appendNode { 
    bar { 
        baz()
    } 
}

println XmlUtil.serialize( xml )
dmahapatro
  • 49,365
  • 7
  • 88
  • 117