2

I work with XML using XmlSlurper. It works fine until I update it. The appendNode doesn't reflect the size.

How to worked with XmlSlurper after structure update?

XML definition:

def CAR_RECORDS = '''
    <records>
      <car name='HSV Maloo' make='Holden' year='2006'>
        <country>Australia</country>
        <record type='speed'>Production Pickup Truck with speed of 271kph</record>
      </car>
      <car name='P50' make='Peel' year='1962'>
        <country>Isle of Man</country>
        <record type='size'>Smallest Street-Legal Car at 99cm wide and 59 kg in weight</record>
      </car>
      <car name='Royale' make='Bugatti' year='1931'>
        <country>France</country>
        <record type='price'>Most Valuable Car at $15 million</record>
      </car>
    </records>
  '''

Code witch fails:

def records = new XmlSlurper().parseText(CAR_RECORDS)
records.appendNode( { car(make:'BMW') } ) 
assert 4 == records.car.size() //fails!!! size == 3

Print out XML including BMW car

def xmlOut = new groovy.xml.StreamingMarkupBuilder()    
def temp = xmlOut.bind{ 
        mkp.yield records   
} 
​println temp​
amra
  • 16,125
  • 7
  • 50
  • 47

2 Answers2

5

You can read the newly created structure again using the XmlSlurper.

...

records = new XmlSlurper().parseText(temp as String)
assert 4 == records.car.size()
mrhaki
  • 3,512
  • 1
  • 14
  • 8
0

Try this

records = records.appendNode( { car(make:'BMW') } ) 

update: actually this code doesn't compile(see comments) so i'll post my own workaround results later.

In some project i used template string like:

static final String template = '<row><someList></someList></row>'

You can append node like that(lang Groovy):

    def row = new XmlSlurper().parseText(template);
    row.someList.appendNode(){
      ListElement(){
        field1('A')
        field2('B')
        field3('B')
      }
    }
Pavel Repin
  • 253
  • 3
  • 11
  • This code doesn't work. `records` is `GPathResult` object and `appendNode` method return `void`. See http://groovy.codehaus.org/api/groovy/util/slurpersupport/GPathResult.html#appendNode(java.lang.Object) – amra Sep 23 '11 at 16:31
  • yep. you are right. i was fighting with this problem(not compilation error that i made in answer LOL) about 5 months ago. i'll check my code and post some useful comments later for future XMLSlurper users. – Pavel Repin Jan 27 '12 at 13:49
  • Folks, I have a very similiar situation and I'm still fighting with XMLSlurper stuff and appendNode.. this simply didn't work!!!.. and not sure if something other XML parser would work with Groovy - SOAP-UI mainly. – Jrr Jul 26 '16 at 15:38