0

I'm trying to read and change one specific node of a pom.xml using XmlSlurper but I'm unable to change the original file.

The original pom.xml:

<myFile>
...
   <tag1>
    <tag2>
        <name1>something1</name1>
        <name2>something2</name2>
        <name3>something3</name3>
    </tag2>
   </tag1>
...
</myFile>

I need to replace the existing information and add some more to something like this:

<myFile>
...
   <tag1>
    <tag2>
        <name1>something4</name1>
        <name2>something5</name2>
        <name3>something6</name3>
        <name4>something7</name4>
    </tag2>
   </tag1>
...
</myFile>

I have tried multiple things and the closest I got is this code:

def file = new File('pom.xml')
def xml = new XmlSlurper().parse(file)

xml.tag1.tag2[0].replaceNode { 
        name1("something1")
        name2("something2")
        name3("something3")
        name4("something4")
        }


def writer = new FileWriter(file)
new XmlNodePrinter(new PrintWriter(writer)).print(xml)

But when I run this code the original pom.xml is empty. I know there is a lot of posts about this but I couldn't make it work. What am I doing wrong?

1 Answers1

1

You need to modify replaceNode content so that tag2 is replaced with different version of tag2 and use different way of writing to file, like this:

import groovy.xml.XmlSlurper

def file = new File('pom.xml')
def xml = new XmlSlurper().parse(file)

xml.tag1.tag2.replaceNode {
    tag2 {
        name1("something1")
        name2("something2")
        name3("something3")
        name4("something4")
        name5("something5")
    }
}

def writer = new FileWriter(file)
groovy.xml.XmlUtil.serialize(xml, writer)

It is cleaner way and it allows you to print instead of writing to file, when you just want to play around with updates: println groovy.xml.XmlUtil.serialize(xml)