GPath expression for finding all attribute values by name

2k Views Asked by At

Looking for GPath expression to get list of attribute values using the attribute name:

def xmltxt = """<reports>
    <report category="weather">sunny</report>
    <report category="sports">golf</report>
    <report category="business">
      <subreport category="deals">wallstreet</subreport>
    </report>
    <report>NA</report>
    <report category="life">gossip</report>
 </reports>"""

..when searching for all category attributes, I want to get back this, regardless of where category attributes exists in the document:

[weather, sports, business, deals, life]

...but all my attempts retrieve more than what I want, appears it's returning nodes that don't have category attributes; I can remove the empty elements from the list, but I'd like to know why this is happening.

[, weather, sports, business, deals, , life]

  def names = xml.'**'.findAll{
     it.@category        
  }.collect{
     it.@category
  }
1

There are 1 best solutions below

5
On BEST ANSWER
def parsed = new XmlParser().parseText( xmltxt )
parsed.'**'*.attribute( 'category' ).findAll()

should do.

Here you go, with XmlSlurper solution:

def parsed = new XmlSlurper().parseText( xmltxt )
parsed.'**'*.attributes().findResults { it.category }