Get value of an XML attribute with Groovy (gpath)

前端 未结 1 1779
抹茶落季
抹茶落季 2021-01-15 02:26

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

   <         


        
1条回答
  •  一生所求
    2021-01-15 02:45

    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 = '''
    
        
        
        
    
    '''
    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
        }
    }
    

    0 讨论(0)
提交回复
热议问题