Search code examples
xmlgroovyxml-parsingxmlslurper

How to find all elements by a tag and attribute in Groovy using XmlSlurper


We have a xml which looks like below

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<GeneratorRun>
<param>
    <comGrp name="Abc">            
        <component name="A">
            <genFiles>
                <file location="xyz/a/b/x.h" checksum="1558926677"/>
                <file location="xyz/a/b/y.h" checksum="2621886660"/>                   
            </genFiles>
        </component>
        <component name="B">
            <genFiles>
                <file location=""xyz/a/b/z.h" checksum="1558926677"/>                   
            </genFiles>
        </component>
    </comGrp>
</param>

I need to get all file location information which are under genFiles. WHats the experession for the same.

What I tries so far is below which didn't give the result

GPathResult xmlContent = new XmlSlurper().parse(config.genSourceRootDir.resolve('par.xml').toFile())
  List<String> generatedFiles = xmlContent.'**'[email protected]()

Solution

  • You need to first find the nodes, then query their attributes

    something like this:

    List<String> generatedFiles = xmlContent.'**'
        .findAll { it.name() == 'genFiles' }
        .file*.collectMany { [it.@location] }.flatten()