Question

I want to create a xml like this:

<root>
  <level1>
    <levl2/>
  </level1>
</root>

Here is my groovy code:

def root="<root/>"
def l1 = "<level1/>"
def l2 = "<level2/>"

def dom = new XmlSlurper(false, false).parseText(root)
dom.appendNode(new XmlSlurper().parseText(l1))
dom.level1.appendNode(new XmlSlurper().parseText(l2))
def sw = new StringWriter()
XmlUtil.serialize(dom, sw)
println sw.toString()

The actual result of my code is like this:

<root>
  <level1/>
</root>

Could anyone tell me what's wrong?

Was it helpful?

Solution

Because appendNode() always appends at the end of the document, so you do not need to specify the last node. In your example, since l2 has to be added as a child to l1 so using leftShift will be an easier option:

def root="<root/>"
def l1 = "<level1/>"
def l2 = "<level2/>"

def dom = new XmlSlurper(false, false).parseText(root)

dom << ( new XmlSlurper().parseText( l1 ) << new XmlSlurper().parseText( l2 ) )

def sw = new StringWriter()
XmlUtil.serialize(dom, sw)
println sw.toString()

Is there any reason you cannot use like this:

dom.root {
    level1 {
        level2 { }
    }
}

Normally, it is done using MarkupBuilder as:

def swr = new StringWriter()
def markup = new groovy.xml.MarkupBuilder(swr)
markup.root {
    level1 {
        level2 { }
    }
}


println swr

What is the intention here using appendNode?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top