Reading XML content with namespaces
XML namespaces, in a way, are similar to Java packages because they allow creating an additional context for grouping a set of elements. We already noted some differences in namespace handling for the XmlParser
and XmlSlurper
classes in the Reading XML using XmlParser and Reading XML using XmlSlurper recipes.
In this recipe, we dig a bit deeper into the details of XML namespace support in Groovy.
Getting ready
Let's use the same shakespeare.xml
file we used for the Reading XML using XmlParser and Reading XML using XmlSlurper recipes.
How to do it...
XmlParser
requires you to specify an element name exactly as it appears in the parsed XML, including the name of the prefix used in the actual XML content. This makes the code fragile because the namespace prefixes have to match.
In order to make code that is based on
XmlParser
more reliable in respect to namespaces, we can resort to thegroovy.xml.Namespace
class as shown in the following code:import groovy.xml...