Skip to content

Instantly share code, notes, and snippets.

@Joxebus
Last active January 18, 2021 20:59
Show Gist options
  • Save Joxebus/6790c71e61695918d7ad224a5cc4c0e7 to your computer and use it in GitHub Desktop.
Save Joxebus/6790c71e61695918d7ad224a5cc4c0e7 to your computer and use it in GitHub Desktop.
Working with XML on Groovy, this gist are a series of examples, also see the difference between XmlSlurper and XmlParser here: https://stackoverflow.com/a/7621603/14757065 for full samples visit: https://groovy-lang.org/processing-xml.html
import groovy.util.XmlSlurper
String xml = '''
<people>
<person age='33'>
<name>Omar</name>
</person>
<person age='30'>
<name>Maria</name>
</person>
</people>
'''
def people = new XmlSlurper().parseText(xml)
assert people.person[0].name == 'Omar'
assert people.person[1].name == 'Maria'
assert people.person*.@age == [33, 30]
import groovy.util.XmlParser
String xml = '''
<people>
<person age='33'>
<name>Omar</name>
</person>
<person age='30'>
<name>Maria</name>
</person>
</people>
'''
def people = new XmlParser().parseText(xml)
assert people.person[0].name.text() == 'Omar'
assert people.person[1].name.text() == 'Mary'
assert people.person*.@age == ['33', '30']
import groovy.xml.MarkupBuilder
def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
xml.people() {
person(lastname:'Bautista', age:33) {
name('Omar')
from(city: 'Merida')
}
person( lastname:'Valenzuela', age:29) {
name('Jorge')
from(city: 'Guanajuato')
}
}
println writer
import groovy.xml.StreamingMarkupBuilder
def xml = new StreamingMarkupBuilder().bind {
people {
person(lastname:'Bautista', age:33) {
name('Omar')
from(city: 'Merida')
}
person( lastname:'Valenzuela', age:29) {
name('Jorge')
from(city: 'Guanajuato')
}
}
}
println xml
import groovy.util.*
URL feedXML = 'https://refind.com/chrismessina.rss?amount=10'.toURL()
def feed = new XmlSlurper().parseText(feedXML.text)
feed.channel.item.each { entry ->
println """
title: ${entry.title}
url: ${entry.link}
created: ${entry.pubDate}
"""
}
assert feed.channel.item.size() == 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment