Replace XML Node with another instance of Node

时间:2016-04-04 17:03:53

标签: xml groovy

I use groovy to parse a XML file using XmlParser. Using the dot notation I can receive the desired node as Node instances.

For my use case a Node is cloned, edited and will replace the original node once the editing is over.

The Node Object has a replaceNode implemented, which expects a closure, with this documentation:

Replaces the current node with nodes defined using builder-style notation via a Closure.

@param c A Closure defining the new nodes using builder-style notation.

My question is, how can I replace one Node instance against another instace of Node?

This is what I do right now, which of course is not working:

Node referenceNode
Node editedNode
referenceNode.replaceNode {
    editedNode
}

As the plus() method also excpects the same syntax, this is a bit of a struggle for me.

Here is a related question with was solved using XmlSlurper, which I don't want to do: Groovy: Node.replaceNode with Node?

1 个答案:

答案 0 :(得分:4)

Just call replaceNode with the node you want to replace it with:

import groovy.xml.*

def xml = '''
<root>
    <user><name>a</name></user>
    <user><name>b</name></user>
    <user><name>c</name></user>    
</root>'''

parser = new XmlParser().parseText(xml)

Node newNode = parser.user[2].clone()
newNode.@something = 'woo'
parser.user[1].replaceNode(newNode)

println XmlUtil.serialize(parser)

That prints:

<?xml version="1.0" encoding="UTF-8"?><root>
  <user>
    <name>a</name>
  </user>
  <user something="woo">
    <name>c</name>
  </user>
  <user>
    <name>c</name>
  </user>
</root>