XmlParser and XmlSluper are used for parsing XML with Groovy. Both have the same
approach to parse an xml.
Both come with a bunch of overloaded parse methods plus some special methods such
as parseText , parseFile and others.
XmlSlurper
def text = '''
<list>
<technology>
<name>Groovy</name>
</technology>
</list>
'''
def list = new XmlSlurper().parseText(text)
assert list instanceof groovy.util.slurpersupport.GPathResult
assert list.technology.name == 'Groovy'
Parsing the XML an returning the root node as a GPathResult
Checking we’re using a GPathResult
Traversing the tree in a GPath style
XmlParser
18/71
def text = '''
<list>
<technology>
<name>Groovy</name>
</technology>
</list>
'''
def list = new XmlParser().parseText(text)
assert list instanceof groovy.util.Node
assert list.technology.name.text() == 'Groovy'
Parsing the XML an returning the root node as a Node
Checking we’re using a Node
Traversing the tree in a GPath style
Let’s see the similarities between XMLParser and XMLSlurper first:
Both are based on SAX so they both are low memory footprint
Both can update/transform the XML
But they have key differences:
XmlSlurper evaluates the structure lazily. So if you update the xml you’ll have to
evaluate the whole tree again.
XmlSlurper returns GPathResult instances when parsing XML
XmlParser returns Node objects when parsing XML
When to use one or the another?
If you want to transform an existing document to another then XmlSlurper will be
the choice
If you want to update and read at the same time then XmlParser is the choice.