Groovy, XML and Namespaces

I just had to work with Groovy (creating a Pipeline in Jenkins V2) where we needed to handle XML documents. In fact we were reading the documents from disk but just to keep that little example easy I skip this and just create a text variable which includes the XML fracment. What I want to show is how to use the XMLParser together with a XML document which uses namespaces. The sample I’m using is from I’ve just added some namespaces. Just node the difference regarding the namespace definitions in line 9 + 10 and take a look on the different style of the GPath statements in line 15.

def text = '''<!?xml version="1.0" encoding="UTF-8"?>
<rootElement xmlns:n1=""

def n1 = new groovy.xml.Namespace("", 'n1')
def n2 = new groovy.xml.Namespace("", 'n2')

def list = new XmlParser().parseText(text)

assert list instanceof groovy.util.Node
assert list[][].text() == 'Groovy'

println 'Content of name is: '+list[][].text()
This entry was posted in Groovy, PC-Krams and tagged , , . Bookmark the permalink.

Leave a Reply