groovy/XML: Replace a node by another one

1.7k views Asked by At

I try to replace an XML node by another one by using XmlSlurper (or XmlParser).

The original XML:

<myXml>
  ...
  <myNode>
    <Name>name1</Name>
    <Name>name2</Name>
    <Name>name3</Name>
 </myNode>
 ...
</myXml>

The list that contains the items to build my new node

def namelist = ['name4','name5','name6','name7']

What I want to have

<myXml>
  ...
  <myNode>
    <Name>name4</Name>
    <Name>name5</Name>
    <Name>name6</Name>
    <Name>name7</Name>
 </myNode>
 ...
</myXml>

To remove the node I tried this but the node is still present:

def myXml = new XmlSlurper().parseText(xml)
myXml.myNode[0].replaceNode {}

Then I didn't find a solution to create the new node by using a list.

1

There are 1 answers

1
Opal On BEST ANSWER

Here you go:

import groovy.xml.*

def xml = '''<myXml>
  <myNode>
    <Name>name1</Name>
    <Name>name2</Name>
    <Name>name3</Name>
 </myNode>
</myXml>'''
def namelist = ['name4','name5','name6','name7']
def slurped = new XmlSlurper().parseText(xml)

slurped.myNode.replaceNode {
 myNode {
    namelist.collect { n ->
      Name "$n"
    }
 }
}

new StreamingMarkupBuilder().bind {
    mkp.yield slurped
}.toString()

The node was in fact replaced but you need to serialize XML to see it.