Xu Hao
Xu Hao

Reputation: 23

how i use groovy to insert a node which has attribute and value

there is a simple xml, for example:

def rootNode = new XmlSlurper().parseText(
'<root>
    <one a1="uno!"/>
    <two>Some text!</two>
 </root>' )

how can i insert a node

<three type='c'>2334</three>

into root?

i have use this way to insert

rootNode.appendNode{three(type:'c') 2334}
rootNode = new XmlSlurper().parseText(rootNode)

but it return exception.

Upvotes: 2

Views: 738

Answers (1)

Rao
Rao

Reputation: 21369

Below script should give you desired result:

change from yours: three (type:'c', 2334)

import groovy.xml.*
def rootNode = new XmlSlurper().parseText('<root><one a1="uno!"/><two>Some text!</two></root>' )
rootNode.appendNode {
    three (type:'c', 2334)
}
def newRootNode = new StreamingMarkupBuilder().bind {mkp.yield rootNode}.toString()
println newRootNode

Output: <root><one a1='uno!'></one><two>Some text!</two><three type='c'>2334</three></root>

Upvotes: 1

Related Questions