【问题标题】:groovy filter xml and printgroovy 过滤 xml 并打印
【发布时间】:2014-03-10 09:23:37
【问题描述】:

我想读取 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
      } )
}

【问题讨论】:

    标签: xml groovy filter


    【解决方案1】:

    你可以这样做:

    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>
    

    【讨论】:

    • 谢谢。所以诀窍是添加 children()。结果类型是 GPathResult。
    • 是的,如果你想在整个树中搜索type="groceries" 节点,类似于root.'**'.findAll { it.@type == 'groceries' }
    猜你喜欢
    • 2021-05-15
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 2011-03-15
    • 1970-01-01
    • 1970-01-01
    • 2018-04-06
    相关资源
    最近更新 更多