Search code examples
xmlgroovy

Groovy: Find and replace all node names


Considering I have the following XML structure:

<Header>
   <Parent1>
       <Line> ABC </Line>
   </Parent1>
   <Parent1>
       <Line> CDE </Line>
   </Parent1>
   <Parent2>
       <Line> EFG </Line>
   </Parent2>
</Header>

I would want all Parent1 parent nodes to be changed to Parent2. Like so:

<Header>
   <Parent2>
       <Line> ABC </Line>
   </Parent2>
   <Parent2>
       <Line> CDE </Line>
   </Parent2>
   <Parent2>
       <Line> EFG </Line>
   </Parent2>
</Header>

Is there a simple way to do this requirement in Groovy?


Solution

  • You can use XmlSlurper to do this.

    def xml = '''<?xml version='1.0' encoding='utf-8'?>
    <Header>
       <Parent1>
           <Line> ABC </Line>
       </Parent1>
       <Parent1>
           <Line> CDE </Line>
       </Parent1>
       <Parent2>
           <Line> EFG </Line>
       </Parent2>
    </Header>
    '''
    
    def result = new XmlSlurper().parseText(xml)
    
    result.Parent1.replaceNode {
        'Parent2'(it.attributes(), it.children())
    }
    
    println(XmlUtil.serialize(result))
    

    You can find more information in XML Processing documentation.