N.I N.I - 3 months ago 14
Groovy Question

Remove certain tags in XML using Groovy

This is the sample code in which im trying to remove the

<notification>
and
</notification>
. I just want the
<one>
<two>
tags.

import groovy.xml.MarkupBuilder
import groovy.xml.XmlUtil
import java.util.*

def s_xml=new StringWriter()
def builder = new groovy.xml.MarkupBuilder(s_xml)
def tempMap = [one:'yes', two: 'Java', three:'Scala']
builder.notification{
tempMap.each(){ key, value ->
"${key}""${value}"
}
}
log.info s_xml


output:

<notification>
<one>Groovy1</one>
<two>Java</two>
<three>Scala</three>
</notification>


i want the output as:

<one>Groovy1</one>
<two>Java</two>
<three>Scala</three>


If I remove the
.notification
from
builder.notification{
, the output becomes:

<call>
<one>yes</one>
<two>Java</two>
<three>Scala</three>
</call>


so by default it puts a tag which I don't want.

Answer

please consider that every xml-document has a root node wikipedia: root element

if you don't want it, concat it "by hand":

String sXml = ""
tempMap.each { key, value ->
    sXml += "<$key>$value</$key>"
}

or if you would like to use a StringBuilder:

def sXml = ''<<''
tempMap.each { key, value ->
    sXml << "<$key>$value</$key>"
}
Comments