groovy过滤器xml和打印 [英] groovy filter xml and print
问题描述
我想读取xml,过滤一些特定的类别并将结果写入屏幕或以xml格式存档。我无法找到XmlUtil.serialize或StreamingMarkupBuilder的正确类型。我在哪里可以找到XmlUtil.serialize或StreamingMarkupBuilder?
def input ='''
< shopping>
< category type =groceries>
< item>巧克力< / item>
< item> Coffee< / item>
< / category>
< category type =supplies>
< item>纸张< / item>
< item quantity =4>钢笔< / item>
< / category>
< category type =present>
< item when =Aug 10>凯瑟琳的生日< / item>
< / category>
< / shopping>
'''
def root = new XmlSlurper()。parseText(input)
$ b $ def groceries = root.shopping.findAll {it。@ type == 'groceries'}
//这里我喜欢将过滤结果打印到文件/屏幕
/ **< category type =groceries>
< item>巧克力< / item>
< item> Coffee< / item>
< / category>
** /
println serializeXml(root)//我想在这里写'杂货',但类型不是XmlUtil.serialize或StreamingMarkupBuilder的
def String serializeXml(GPathResult xml){
XmlUtil.serialize(new StreamingMarkupBuilder()。bind {
mkp.yield xml
})
}
$您可以这样做:
<$>
$ b 解决方案 p $ p $ import groovy.xml。*
$ b $ def def root = new XmlSlurper()。parseText(input)
$ b $ def groceries = root.children ().findAll {it。@ type =='groceries'}
println XmlUtil.serialize(groceries)
<?xml version =1.0encoding =UTF- 8?>< category type =groceries>
< item>巧克力< / item>
< item> Coffee< / item>
< / category>
或者您可以:
<$ p
$打印:
< category type ='groceries'>< item>巧克力< / item>< item>咖啡和LT; /项目>< /类别>
I would like to read xml, filter for some specific 'category' and write the result to screen or to file as xml. I am not able to find the right type for XmlUtil.serialize or StreamingMarkupBuilder. Where can I find the XmlUtil.serialize or 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
} )
}
You can do:
import groovy.xml.*
def root = new XmlSlurper().parseText( input )
def groceries = root.children().findAll { it.@type == 'groceries' }
println XmlUtil.serialize( groceries )
To print:
<?xml version="1.0" encoding="UTF-8"?><category type="groceries">
<item>Chocolate</item>
<item>Coffee</item>
</category>
Or you could do:
println new StreamingMarkupBuilder().bind { mkp.yield groceries }
To print:
<category type='groceries'><item>Chocolate</item><item>Coffee</item></category>
这篇关于groovy过滤器xml和打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!