Search code examples
xmlgroovyxmlslurper

Groovy XMLSlurper how to append a child element after an existing element?


I'm using XMLSlurper to parse a XML in Groovy.

An element should be added to the parsed XML (GPathResult instance), but the new element should be at a specific position, after an existing element, to be compliant with the XML Schema.

Right now the only thing that works is to append the new node at the end of the parsed XML, that violates the XSD.

Is there a way to append the new element after an exiting element? Something like "appendSibling()"?

The structure is like this:

<root>
  <name>xxx</name>
  <state>xxx</state>
</root>

And I need "id" after "name" and under "root":

<root>
  <name>xxx</name>
  <id>xxx</id>
  <state>xxx</state>
</root>

Solution

  • Found a simple solution using replaceNode that is almost a one liner. This adds the require node after an existing one that is overwritten with the sample node + the new node. The only issue is getting the new node back doesn't work because XmlSlurper is lazy!

    import groovy.util.XmlSlurper
    
    def xml = new XmlSlurper().parseText('''
    <root>
      <name>xxx</name>
      <state>xxx</state>
    </root>
    ''')
    
    xml.name.replaceNode { node ->
       mkp.yield(node)
       id('xxxx')
    }
    
    println xml.children()*.name() // new id node doesn't get printted because it was not evaluated (XmlSlurper is lazy!)
    
    groovy.xml.XmlUtil.serialize( xml )