groovy过滤器xml和打印

时间:2014-03-10 09:23:38

标签: xml groovy filter

我想读取xml,过滤某些特定的“类别”并将结果写入屏幕或文件为xml。我无法为XmlUtil.serialize或StreamingMarkupBuilder找到正确的类型。我在哪里可以找到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
      } )
}

1 个答案:

答案 0 :(得分:0)

你可以这样做:

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>