You probably want something like this:
def response = new XmlSlurper().parseText(books)
response.'**'.findAll{ [email protected]() }.each {
it.@isavailable = 'true'
}
println groovy.xml.XmlUtil.serialize(response)
On Mon, Jul 4, 2016 at 3:05 PM, GroovyBeginner <[email protected]> wrote:
> I'm trying to accomplish adding the attribute dynamically to the current xml
> node if the attribute `"available"` exists using Groovy and XmlSlurper. Is
> there a way to do this?Here is the XML structure
>
> def books = '''
> <response version-api="2.0">
> <value>
> <books>
> <book available="20" id="1">
> <title>Don Xijote</title>
> <author available="20" id="1">Manuel De
> Cervantes</author>
> </book>
> <book id="2">
> <title>Catcher in the Rye</title>
> <author id="2">JD Salinger</author>
> </book>
> </books>
> <Amount available="" id="3"></Amount>
> </value>
> </response>
> '''
> Here is the code am trying out
>
> def response = new XmlSlurper().parseText(books)
> def responsenew = response.value.books.'**'.find { node->
> if(node.attributes().get('available')!=null)
> {
> println " ${node.name()}: ${node.text()}"
> }
> else
> {
> println " ${node.name()}: ${node.text()}"
> }
> }
> My Output should be altered as following:
>
> <response version-api="2.0">
> <value>
> <books>
> <book available="20" id="1" isavailable="true">
> <title>Don Xijote</title>
> <author available="20" id="1"
> isavailable="true">Manuel De Cervantes</author>
> </book>
> <book id="2">
> <title>Catcher in the Rye</title>
> <author id="2">JD Salinger</author>
> </book>
> </books>
> <Amount available="" id="3"
> isavailable="true"></Amount>
> </value>
> </response>
>
>
>
> --
> View this message in context:
> http://groovy.329449.n5.nabble.com/Groovy-Add-Attribute-to-XML-Dynamically-tp5733759.html
> Sent from the Groovy Dev mailing list archive at Nabble.com.