使用Groovy删除XML中的某些标记

时间:2016-08-31 16:09:33

标签: xml groovy

这是我尝试删除<notification></notification>的示例代码。我只想要<one> <two>代码。

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

输出:

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

我希望输出为:

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

如果我从.notification删除builder.notification{,则输出变为:

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

所以默认情况下它会放置一个我不想要的标签。

2 个答案:

答案 0 :(得分:0)

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>"
}

答案 1 :(得分:0)

You can use the MarkupBuilder's with method so it doesn't generate a call root node:

import groovy.xml.* 

sw = new StringWriter()
mb = new MarkupBuilder(sw).with {
    one "java"
    two "groovy"
}

assert sw.toString() == """<one>java</one>
<two>groovy</two>"""

Source: groovy's mailing list.