groovy filter xml and print -
i read xml, filter specific 'category' , write result screen or file xml. not able find right type xmlutil.serialize or streamingmarkupbuilder. can find 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 print filtered result file/screen /** <category type="groceries"> <item>chocolate</item> <item>coffee</item> </category> **/ println serializexml(root) // write here 'groceries' type not 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 do:
println new streamingmarkupbuilder().bind { mkp.yield groceries }
to print:
<category type='groceries'><item>chocolate</item><item>coffee</item></category>
Comments
Post a Comment