Note that there are some explanatory texts on larger screens.

plurals
  1. POGroovy: how to insert a node at the beginning of a list of elements in XML read in using XMLSlurper()
    primarykey
    data
    text
    <p>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 <strong>at the beginning</strong> of a series of elements. I have figured out how to <em>replace</em> the first element, and I've figured out how to <em>append</em> 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).</p> <p>For example:</p> <pre><code>@Test void foo() { def xml = """&lt;container&gt; &lt;listofthings&gt; &lt;thing id="100" name="foo"/&gt; &lt;/listofthings&gt; &lt;/container&gt;""" 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 } </code></pre> <p>which yields:</p> <pre><code>&lt;container&gt; &lt;listofthings&gt; &lt;thing id='101' name='bar'/&gt; &lt;thing id='102' name='baz'/&gt; &lt;/listofthings&gt; &lt;/container&gt; </code></pre> <p>What I really want is to insert a node at the <strong>beginning</strong> of <em>listofthings</em>, i.e. something to replace the call to <em>replaceNode</em> 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.</p> <p>(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)</p> <p>Edit: I'm using 1.7.5, that's bundled with Eclipse, if it matters.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload