Himanshu Yadav
Himanshu Yadav

Reputation: 13585

Groovy: Delete/Add Xml nodes

It is an extension of my previous question. If I get input xml like this

<ClientInformation>
        <FirstName>Steve</FirstName>
        <LastName>Jobs</LastName>
        <MiddleName/>
        <DateOfBirth>09/18/2013</DateOfBirth>
        <RoleTypeCT>OWN</RoleTypeCT>
        <RoleTypeCT>IBE</RoleTypeCT>        
        <RoleTypeCT>Insured</RoleTypeCT>
</ClientInformation>

Output Xml should be

<ClientInformation>
            <FirstName>Steve</FirstName>
            <LastName>Jobs</LastName>
            <MiddleName/>
            <DateOfBirth>09/18/2013</DateOfBirth>
            <RoleTypeCT>OWN</RoleTypeCT>
    </ClientInformation>
<ClientInformation>
            <FirstName>Steve</FirstName>
            <LastName>Jobs</LastName>
            <MiddleName/>
            <DateOfBirth>09/18/2013</DateOfBirth>
            <RoleTypeCT>IBE</RoleTypeCT>        
    </ClientInformation>
<ClientInformation>
            <FirstName>Steve</FirstName>
            <LastName>Jobs</LastName>
            <MiddleName/>
            <DateOfBirth>09/18/2013</DateOfBirth>   
            <RoleTypeCT>Insured</RoleTypeCT>
    </ClientInformation>

Groovy Code

if(it.name()=="ClientInformation") {
  println it.RoleTypeCT.size() //prints 3 on console

}

I am thinking of following steps:

  1. Assign it to a local variable. def clientInfo = it
  2. Delete all the RoleTypeCT nodes from clientInfo. Tried clientInfo.RoleTypeCT.replaceNode{} but it gave me error.
  3. For each RoleTypeCT in original it, add RoleTypeCT to clientInfo. Something like

    it.RoleTypeCT.each { def roleType = it clientInfo.appendNode(roleType) }

If this approach is ok then how would delete all RoleTypeCT nodes at the first place?

Upvotes: 0

Views: 519

Answers (1)

tim_yates
tim_yates

Reputation: 171114

Here's how you remove all the RoleTypeCT nodes, however I still have concerns you're walking the wrong path (see comment to question)

import groovy.xml.*

def client = new XmlSlurper().parseText( xml )

client.RoleTypeCT*.replaceNode {}

println XmlUtil.serialize( client )

Upvotes: 1

Related Questions