Groovy: how to insert a node at the beginning of a list of elements in XML read using XMLSlurper ()

I'm probably missing something obvious, since I'm a noob with Groovy, but I searched, but didn't find what I was looking for. I have a test class where I read in XML; I want to insert an element at the beginning of a series of elements. I figured out how to replace the first element, and I figured out how to add a node to the end of the list, but I can't imagine how to insert an element at the beginning of the list (or, ideally, an arbitrary position).

For instance:

@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 gives:

<container>
   <listofthings>
     <thing id='101' name='bar'/>
     <thing id='102' name='baz'/>
   </listofthings>
</container>

node , .. - replaceNode, 101 100 , , node n- .

(, ? StreamingMarkupBuilder , )

: 1.7.5, Eclipse, .

+5
1

, thing xml , , :

// function to take a single line xml output, and make it pretty
String renderFormattedXml( String xml ){
  def stringWriter = new StringWriter()
  def node = new XmlParser().parseText( xml )
  new XmlNodePrinter( new PrintWriter( stringWriter ) ).print( node )
  stringWriter.toString()
}

def xml = """<container>
               <listofthings>
                   <thing id="100" name="foo"/>
               </listofthings>
             </container>"""

def root = new XmlSlurper().parseText(xml)

def things = root.listofthings*.thing

// Insert one at pos 0
things.add( 0, { thing( id:98, name:'tim' ) } )

// And one at the end
things.add( { thing( id:999, name:'zebra' ) } )

// And one at position 1
things.add( 1, { thing( id:99, name:'groovy' ) } )

def outputBuilder = new groovy.xml.StreamingMarkupBuilder()
String result = outputBuilder.bind {
  container {
    listofthings {
      mkp.yield things
    }
  }
}
println renderFormattedXml( result )

<container>
  <listofthings>
    <thing id="98" name="tim"/>
    <thing id="99" name="groovy"/>
    <thing id="100" name="foo"/>
    <thing id="999" name="zebra"/>
  </listofthings>
</container>
+7

All Articles