Vik
Vik

Reputation: 9289

groovy rename node issue using xmlSlurper

i have a xml like below where i just need to rename the node name to another.

<a x=1>
  <b>c</b>
</a>

and i want to change it to

<p:a x=1>
  <b>c</b>
</p:a>

i need to do it using xmlSlurper so how do i do it? how can i do the node rename. Does it need to rewrite the whole xml into another document etc? or can i do it within the document?

def xmlDoc = new XmlSlurper(false,false).parse('my.xml')

Upvotes: 0

Views: 1117

Answers (2)

BugOrFeature
BugOrFeature

Reputation: 329

First you need to fix your XML. The value for attribute x needs quotes:

<a x="1">
  <b>c</b>
</a>

Then to rename the root node:

xmlDoc.replaceNode {
    'p:a'(it.children())
}

Upvotes: 2

David M. Karr
David M. Karr

Reputation: 15225

XmlSlurper reads XML into an object structure. Once you read it in, you can do whatever you want with it, but XmlSlurper has nothing to do with that.

Use MarkupBuilder to write out XML from that read-in object structure.

Upvotes: -1

Related Questions