Nupur Jaiswal Nupur Jaiswal - 4 months ago 44
Groovy Question

groovy.lang.MissingMethodException: No signature of method: groovy.util.slurpersupport.NodeChild.add()

I am a newbie to groovy. I'm trying to run this groovy script:

def inxml = "<?xml version='1.0' encoding='UTF-8' standalone='yes' ?> <doc><extension source='ExtractTextStage'>" +
"<field name='DC.Date.Modified'>2006-04-13</field><field name='dc.date'>01-01-2016</field><field name='dc.language'>EN</field></extension>"+
"<extension source='you'>" +
"<field name='dc.date'>02-02-2015</field><field name='dc.language'>EN</field></extension></doc>"

def doc = new XmlSlurper().parseText(inxml)

def date = doc.extension.find{ extension-> extension.@source='ExtractTextStage'}.field.find { field->field.@name == "DC.Date.Modified" }

doc.add("last_modified", date)

print doc​;​


but I'm getting this error:

groovy.lang.MissingMethodException: No signature of method: groovy.util.slurpersupport.NodeChild.add() is applicable for argument types: (java.lang.String, groovy.util.slurpersupport.NodeChild) values: [last_modified, 2006-04-13]
Possible solutions: any(), wait(), name(), pop(), min(), tail()
at Script1.run(Script1.groovy:10)


I want to add a new field named "last_modified" in my XML and assign it the same value as "DC.Date.Modified" field value. Any help would be appreciated.

Answer

Think you need to do something like this:

def inxml = '''<?xml  version='1.0' encoding='UTF-8' standalone='yes'?>
              |<doc>
              |    <extension source='ExtractTextStage'>
              |        <field name='DC.Date.Modified'>2006-04-13</field>
              |        <field  name='dc.date'>01-01-2016</field>
              |        <field  name='dc.language'>EN</field>
              |    </extension>
              |    <extension source='you'>
              |        <field  name='dc.date'>02-02-2015</field>
              |        <field  name='dc.language'>EN</field>
              |    </extension>
              |</doc>'''.stripMargin()

def doc = new XmlSlurper().parseText(inxml)

def date = doc.extension
              .find { extension -> extension.@source='ExtractTextStage'}
              .field
              .find { field -> field.@name == "DC.Date.Modified" }

def newNode = new XmlSlurper().parseText("<last_modified>$date</last_modified>")

doc.appendNode(newNode)

println groovy.xml.XmlUtil.serialize(doc)