Search code examples
groovysoapuixmlslurper

XmlSlurper in Groovy and SOAPUI - Add new element to random location in xml


I'm creating automated tests with soapui and I need to check what happens when I add new groupingNodes on different positions in xml.

I have xml structure similar to this:

<rootNode>
<groupingNode>
    <id>1</id>
    <name>Node 1</name>
    <groupingNode>
        <id>2</id>
        <name>Node 2</name>
        <groupingNode>
            <id>3</id>
            <name>Node 3</name>
        </groupingNode>
    </groupingNode>
</groupingNode>
<groupingNode>
    <id>4</id>
    <name>Node 4</name>
</groupingNode>

And new elements to add:

<groupingNode>
    <id>5</id>
    <name>Node 5</name>
</groupingNode>

In data source I defined several different combinations which node and where to add, so new node in one test case needs to be added to rootNode, in second test case to groupNode with id=3, in third test case to newly created node which is added to rootNode and so on.

So my question is how can I programmatically add new groupingNode element to random position in xml.


Solution

  • I first tried with depth first to find parent groupingNode via his name.

    xml.'**'.find{groupingNode-> groupingNode.name.text() == parentNode}.appendNode( fragmentToAdd )
    

    but this didn't work since i couldn't found all nodes. Later I found out that with this code i can find old nodes, but not new ones. And then after some research I found out that this is problem with XmlSlurper and if I want new nodes to be visible, I need to evaluate xml again 4.1 Adding nodes So after creating new node all i needed to do is:

    def newXML = new StreamingMarkupBuilder().bind { mkp.yield xml}.toString()
    xml= new XmlSlurper( false, true ).parseText( newXML )
    

    and after this I was able to find all groupingNodes with depth first.