Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // g100pon #40 XMLの読み書きを色んな方法で(XmlSlurper->StreamingMarkupBuilder)
- import groovy.xml.StreamingMarkupBuilder
- // パース結果のオブジェクトはGPath型なので、GPath型で定義されているメソッド以外は使えない
- def root = new XmlSlurper().parse('sample.xml')
- def groceries = root.category.findAll{ it.@type == 'groceries' }
- def g = groceries[0]
- g.item.eachWithIndex {item, i ->
- g.item[i] = 'luxury ' + item
- }
- def supplies = root.category.findAll{ it.@type == 'supplies' }
- def pens = supplies[0].item.findAll{ it.text() == 'pen' }
- pens.each { p ->
- p.@quantity = (p.@quantity.toInteger() + 2).toString()
- p.@when = 'Urgent'
- }
- def presents = root.category.find{ it.@type == 'present' }
- presents.replaceNode{ node ->
- category(type:'present'){
- item("mother's birthday")
- item("Monica's birthday", when:'Oct 15')
- }
- }
- def out = new OutputStreamWriter(
- new FileOutputStream("xmlslurper.output.xml"), "UTF-8")
- // XMLの構造しか保持していないので、MarkupBuilderで組み立て直す必要がある
- def outputBuilder = new StreamingMarkupBuilder()
- def writer = outputBuilder.bind{
- mkp.xmlDeclaration()
- mkp.yield(root)
- }
- out << writer
Add Comment
Please, Sign In to add comment