Reading XML using XmlParser
In the previous recipe, Reading XML using XmlSlurper, we learned how to read an XML document using the XmlSlurper
provided by Groovy. Now it's time to look at the other parser available in Groovy, groovy.util.XmlParser
. Its internal implementation differs from groovy.util.XmlSlurper
, but it exposes a very similar API when it comes to document parsing, navigation, and modification.
In this recipe, we will cover the essential usage scenarios for the XmlParser
class and its differences from XmlSlurper
.
How to do it...
Let's use the same shakespeare.xml
file we used in the Reading XML using XmlSlurper recipe.
Reading XML data is very similar to
XmlSlurper
. You need to create an instance ofXmlParser
and pass a file reference to itsparse
method as shown:def xmlSource = new File('shakespeare.xml') def bibliography = new XmlParser().parse(xmlSource)
As with
XmlSlurper
, GPath expressions (see the Searching in XML with GPath recipe for more advanced examples) are also possible...