Get value of an XML attribute with Groovy (gpath)

14,632

I can't tell if you expect there to be multiple matches or if you know there will be exactly one. The following will find them all and print their answer.

source = '''
<root>
    <foo name = 'type' answer  = 'car'/>
    <foo name = 'color' answer = 'red'/>
    <foo name = 'size' answer = 'big'/>
</root>
'''
xml = new XmlParser().parseText(source)

results = xml.findAll { it.@name == 'type' }

results.each {
    println it.@answer
}

I hope that helps.

EDIT:

If you know there is only one you can do something like this...

println xml.find { it.@name == 'type' }.@answer

Yet another option (you have several):

xml = new XmlParser().parseText(source)

xml.each { 
    if(it.@name == 'type') {
        println it.@answer
    }
}
Share:
14,632
user2475310
Author by

user2475310

Updated on June 14, 2022

Comments

  • user2475310
    user2475310 almost 2 years

    Using XmlParser() in groovy. See the following code. I need to print the value of answer when the value of name is type.

       <root>
            <foo name = 'type' answer  = 'car'/>
            <foo name = 'color' answer = 'red'/>
            <foo name = 'size' answer = 'big'/>
        </root>
    

    I need to do something like this:

    def XML = new XmlParser().parseText(XMLstring)
    println XML.root.foo.[where  @name = 'type'].@answer