Nicole Phillips
Nicole Phillips

Reputation: 763

Remove values from xml document using groovy

I have a groovy system batch script that needs to read in an XML document, change the values, and then save it.

I have figured out how to read the value and write it. I cannot figure out for the life of me how to remove 'members' and its values. I need to be able to remove all the members and replace it with a custom filename I just cannot figure it out.

The XML looks like this:

<types>
    <members>*</members>
    <members>Account</members>
    <members>Activity</members>
    <members>Contact</members>
    <members>Task</members>
    <members>User</members>
    <members>ContentVersion</members>
    <name>CustomObject</name>
</types>

I would search for the name "CustomObject" and remove all the sibling's members with this string:

def replace = "MyCustomFile"

So the XML would like this:

<types>
    <members>MyCustomFile</members>
    <name>CustomObject</name>
</types>

I have tried the below code I found online

println "Testing Slurper"
def root = new XmlSlurper().parse(new File(theFile))
root.types.each { types ->
println "names: ${types.name}"
    types.members.each {
        println "members: " + it.text()
    }
}

    println "Testing replace"
    def book = "Booking__c"


    def cleanUpNode(node) {
        println node
        def childs = node.children()

        def remove = []
        childs.each {
            if (it instanceof Node) {

                if (!it.children()) {
                    remove.add it
                } else {
                    cleanUpNode it
                    if (!it.children()) {
                        remove.add it
                    }
                }
            }
        }

        remove.each { node.remove(it) }
    }

    cleanUpNode root.types.name

It is not actually removing anything instead this was the output:

  <tag0:types>
    <tag0:members>*</tag0:members>
    <tag0:members>Account</tag0:members>
    <tag0:members>Activity</tag0:members>
    <tag0:members>Contact</tag0:members>
    <tag0:members>Task</tag0:members>
    <tag0:members>User</tag0:members>
    <tag0:members>ContentVersion</tag0:members>
    <tag0:name>CustomObject</tag0:name>
  </tag0:types>

I am still trying to get the hang of this so any help would be great

Upvotes: 0

Views: 1254

Answers (1)

Edumelzer
Edumelzer

Reputation: 1086

You can do something like this:

List newMembersToAdd = ['myCustomFile', 'anotherCustomFile']

Node xml = new XmlParser(false, false, false).parse("myXml.xml")

xml.members?.each {
    xml.remove it
}

newMembersToAdd.each { String newMember ->
    new Node(xml, 'members', newMember)
}

new File("myNewXml.xml").withWriter { writer ->
    def printer = new XmlNodePrinter( new PrintWriter(writer) )
    printer.preserveWhitespace = true
    printer.print( xml )
}

Upvotes: 1

Related Questions