groovy filter xml and print



我想读取XML,过滤一些特定的'类别',然后将结果写入屏幕或以XML为单位。我找不到适合xmlutil的正确类型。我在哪里可以找到xmlutil.serialize或streamingmarkupbuilder?

def input = '''
<shopping>
    <category type="groceries">
        <item>Chocolate</item>
        <item>Coffee</item>
    </category>
    <category type="supplies">
        <item>Paper</item>
        <item quantity="4">Pens</item>
    </category>
    <category type="present">
        <item when="Aug 10">Kathryn's Birthday</item>
    </category>
</shopping>
'''
def root = new XmlSlurper().parseText(input)
def groceries = root.shopping.findAll{ it.@type == 'groceries' }

// here I like to print the filtered result to file/screen
/**    <category type="groceries">
        <item>Chocolate</item>
        <item>Coffee</item>
    </category>
 **/
println serializeXml(root) // I would like to write here 'groceries' but the type is not something for XmlUtil.serialize or StreamingMarkupBuilder  

def String serializeXml(GPathResult xml){
    XmlUtil.serialize(new StreamingMarkupBuilder().bind {
        mkp.yield xml
      } )
}

您可以做:

import groovy.xml.*
def root = new XmlSlurper().parseText( input )
def groceries = root.children().findAll { it.@type == 'groceries' }
println XmlUtil.serialize( groceries )

打印:

<?xml version="1.0" encoding="UTF-8"?><category type="groceries">
  <item>Chocolate</item>
  <item>Coffee</item>
</category>

,也可以做:

println new StreamingMarkupBuilder().bind { mkp.yield groceries }

打印:

<category type='groceries'><item>Chocolate</item><item>Coffee</item></category>

最新更新