Guest User

Untitled

a guest
Jun 17th, 2018
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. // g100pon #40 XMLの読み書きを色んな方法で(XmlSlurper->StreamingMarkupBuilder)
  2.  
  3. import groovy.xml.StreamingMarkupBuilder
  4.  
  5. // パース結果のオブジェクトはGPath型なので、GPath型で定義されているメソッド以外は使えない
  6. def root = new XmlSlurper().parse('sample.xml')
  7.  
  8. def groceries = root.category.findAll{ it.@type == 'groceries' }
  9. def g = groceries[0]
  10.  
  11. g.item.eachWithIndex {item, i ->
  12. g.item[i] = 'luxury ' + item
  13. }
  14.  
  15. def supplies = root.category.findAll{ it.@type == 'supplies' }
  16. def pens = supplies[0].item.findAll{ it.text() == 'pen' }
  17. pens.each { p ->
  18. p.@quantity = (p.@quantity.toInteger() + 2).toString()
  19. p.@when = 'Urgent'
  20. }
  21.  
  22. def presents = root.category.find{ it.@type == 'present' }
  23. presents.replaceNode{ node ->
  24. category(type:'present'){
  25. item("mother's birthday")
  26. item("Monica's birthday", when:'Oct 15')
  27. }
  28. }
  29.  
  30. def out = new OutputStreamWriter(
  31. new FileOutputStream("xmlslurper.output.xml"), "UTF-8")
  32.  
  33. // XMLの構造しか保持していないので、MarkupBuilderで組み立て直す必要がある
  34. def outputBuilder = new StreamingMarkupBuilder()
  35. def writer = outputBuilder.bind{
  36. mkp.xmlDeclaration()
  37. mkp.yield(root)
  38. }
  39. out << writer
Add Comment
Please, Sign In to add comment