Skip to content

Prepending A Node With Groovy’s XmlParser

A recent question on the Groovy mailing list: how to update an XML document by prepending an element before another?

Not as completely trivial as it might sound.

Groovy’s XMLSlurper only allows for appending a node to a given node’s list of children and so one needs the services of XMLParser.

A teensy bit of fiddling is required, thusly:

def xml = """<x name="fred">
                <y name="bill">
                    <z>
                        <a index="0" size="10"/>
                    </z>
                </y>
                <y name="harry">
                    <z>
                        <a index="0" size="200"/>
                        <a index="1" size="500"/>
                    </z>
                </y>
             </x>"""

def x = new XmlParser().parseText(xml)

x.y.each { y ->
    int numA = 0
    int totalASize = 0
    y.z.a.each { a ->
        numA ++
        totalASize += a.@size.toInteger()
    }
    // add a new node as the 0th child, ie: before <z>
    y.children().add(0, new Node(null, 'summary', [numA:numA,totalASize:totalASize]))
} 

new XmlNodePrinter().print(x)

And the beautiful resultant XML is:

<x name="fred">
  <y name="bill">
    <summary numA="1" totalASize="10"/>
    <z>
      <a index="0" size="10"/>
    </z>
  </y>
  <y name="harry">
    <summary numA="2" totalASize="700"/>
    <z>
      <a index="0" size="200"/>
      <a index="1" size="500"/>
    </z>
  </y>
</x>

Not sure if it’s generally a good idea to depend on the specific ordering of elements in a document but it’s common (Apple’s [nasty] XML Property List format is one example that pops to mind) and–as I’ve shown above–can be done with XMLParser.

Tags: ,

C, Java Enterprise Edition, JEE, J2EE, JBoss, Application Server, Glassfish, JavaServer Pages, JSP, Tag Libraries, Servlets, Enterprise Java Beans, EJB, Java Messaging Service JMS, BEA Weblogic, JBoss, Application Servers, Spring Framework, Groovy, Grails, Griffon, GPars, GAnt, Spock, Gradle, Seam, Open Source, Service Oriented Architectures, SOA, Java 2 Standard Edition, J2SE, Eclipse, Intellij, Oracle Service Bus, OSB