Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GPath expression for finding all attribute values by name

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
  }
like image 910
raffian Avatar asked Dec 21 '25 04:12

raffian


1 Answers

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 }
like image 99
dmahapatro Avatar answered Dec 24 '25 05:12

dmahapatro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!