I’m probably missing something obvious, as I’m a noob with Groovy, but I’ve searched but haven’t found quite what I’m looking for. I have a test class where I’m reading in some XML; I want to insert an element at the beginning of a series of elements. I have figured out how to replace the first element, and I’ve figured out how to append a node to the end of the list, but I can’t seem to grok how to insert an element at the beginning of the list (or ideally, any arbitrary position).
For example:
@Test
void foo()
{
def xml = """<container>
<listofthings>
<thing id="100" name="foo"/>
</listofthings>
</container>"""
def root = new XmlSlurper().parseText(xml)
root.listofthings.thing[0].replaceNode ( { thing(id:101, name:'bar') })
root.listofthings.appendNode ( { thing(id:102, name:'baz') })
def outputBuilder = new groovy.xml.StreamingMarkupBuilder()
String result = outputBuilder.bind { mkp.yield root }
print result
}
which yields:
<container>
<listofthings>
<thing id='101' name='bar'/>
<thing id='102' name='baz'/>
</listofthings>
</container>
What I really want is to insert a node at the beginning of listofthings, i.e. something to replace the call to replaceNode that would instead insert the thing with id 101 before the thing with id 100. I would also be nice if say, I had a longer list, to insert a node after the n’th element.
(Incidentally, is there a way to get the output in a more readable format? The output from StreamingMarkupBuilder all ends up as a single line of text; I reformatted it for clarity above)
Edit: I’m using 1.7.5, that’s bundled with Eclipse, if it matters.
One way you can do this by extracting the
thingelements out of your original xml into a list, manipulating the list, then rebuilding the document with this new list:which prints