How to modify XML node attribute, when iterating through the file with XMLSlurper?

Viewed 4250

In extension to this question, I am now trying to replace the XML node's attribute.

I am already writing to the body of the XML using the below code.

def root = new XmlSlurper().parseText(
'''<root>
     <service>
       <receiver>
         <endpoint type="type1">123</endpoint>
         <endpoint>456</endpoint>
       </receiver>
     </service>
 </root>''')

root.service.each { service ->
service.receiver.endpoint.each { endpoint ->
    endpoint.replaceBody("**"+endpoint.text())
    }
}

println groovy.xml.XmlUtil.serialize( root )

I want to check if the type attribute exists. If it does I want to change its value to say "type2".

Is there an equivalent method to replaceBody() which replaces attributes?

or do I have to implement this differently?

2 Answers
Related