XML parsing using Groovy within a Jenkins Pipeline stage

Posted on August 30th, 2017 at 20:00 PM

One of the major benefits of a Jenkins Pipeline is the high level of integration possible i.e. solutions tend to become single jobs so coding is more transparent. In an attempt to use a single job we recently needed to add XML parsing to a pipeline stage. Groovy's XmlParser worked well if you first copy the contents of an XML file to a string and then parse the string otherwise if you process the file directly the parser complains about the integrity of a perfectly good xml prolog (go figure).

The XML had the following structure:

<tests fails="11">
    <test name="test1">
        <failure> ... </failure> <!-- optional failure element -->

Pipeline code:

def xml = readFile "${env.WORKSPACE}/subdir/test.xml"
// XmlParser may kick off about xml prolog if you dont read xml into string
def tests = new XmlParser().parseText(xml)

echo "FAILS: ${tests.attribute("fails")}"
def failtext = ""
def testname = ""

    testname = it.@name
    // check if test fails
    if (it.failure)
        // get failing test element content
        failtext = it.toString()
        // further processing ...