Groovy Series: GPath


/ Published in: Groovy
Save to your folder(s)



Copy this code and paste it in your HTML
  1. //GPath can be used to easily query XML-based documents or even Object Graphs.
  2. //We start with looking at an XML GPath example.
  3.  
  4. //Let's load the Grails Pocast RSS Feed first.
  5. println "new XmlSluper".center(75, '*')
  6. def feed = new XmlSlurper().parse('http://hansamann.podhost.de/rss')
  7. assert feed.getClass().name == 'groovy.util.slurpersupport.NodeChild'
  8.  
  9.  
  10. //Like using XPath expressions, we can now navigate the tre
  11. //This accesses the first iem element of the RSS channel:
  12. println "Access to node content".center(75, '*')
  13. println feed.channel.item[0].title
  14. println feed.channel.item[0]['title']
  15.  
  16.  
  17. //As in XPath, attributes are accessed with the @ syntax.
  18. println "Access to attribute content".center(75, '*')
  19. println feed.channel.item[0].enclosure.@url
  20. println feed.channel.item[0].enclosure['@url']
  21.  
  22. //Let's see how many podcasts whe have done so far.
  23. println "item element count".center(75, '*')
  24. println feed.channel.item.size()
  25.  
  26. //We can iterate over all items with this
  27. println "All titles below".center(75, '*')
  28. feed.channel.item.each { item ->
  29. println item.title
  30. }
  31.  
  32. //hier will ich die items nach Groovy Series filtern...
  33. //def groovySeries = feed.channel.item.findAll{ return (it.title.indexOf('Groovy Series')) ? true : false;} //wieso geht das nicht... println it.title geht
  34. //println "Found ${groovySeries.size()}"
  35.  
  36. //playing with methods of GPathResult. NodeChild is an extension of GPathResult
  37. assert feed.channel.item[0].enclosure[0].getClass().name == 'groovy.util.slurpersupport.NodeChild'
  38.  
  39. //to call the attributes method, we neet to macke sure that we are operating on a single Node, not a set
  40. feed.channel.item[0].enclosure[0].attributes().each{println it} //works
  41. try {
  42. feed.channel.item[0].enclosure.attributes().each{println it}
  43. } catch (MissingMethodException e)
  44. {
  45. assert feed.channel.item[0].enclosure.getClass().name == 'groovy.util.slurpersupport.NodeChildren'
  46. //above returns a NodeChildren object as it is a path expression for all enclosure tags of the first item tag!
  47. }
  48.  
  49. //let's print all children of an item.
  50. println "All children of item[0]".center(75, '*')
  51. feed.channel.item[0].children().each { println it.name() } //will print tag names contained in item: title, description, author, pubDate, guid, link, enclosure
  52. assert feed.channel.item[0].children().size() == 7
  53.  
  54. //Beispiel mit GPathResult->find / findAll
  55.  
  56.  
  57. //evtl. xmlslurper dazu verwenden ein xml-doc zu veraendern??

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.