tags:

views:

379

answers:

2

While trying to parse RSS feeds in Groovy, I found a GPath example using wildcards:

def text = """ 
<data> 
   <common-tables> 
    <table name="address"/> 
    <table name="phone"/> 
  </common-tables> 

  <special-tables> 
    <table name="person"/> 
  </special-tables> 

  <other-tables> 
    <table name="business"/> 
  </other-tables> 
</data> 
""" 

def xml = new XmlParser().parse(new ByteArrayInputStream(text.getBytes())) 
def tables = xml.'**'.table.findAll{ it.parent().name() == 
"special-tables" || it.parent().name

(from http://old.nabble.com/Q:-Avoiding-XPath---using-GPath-td19087210.html)

It looks like a funny use of the 'spread-dot' operator. I can't find any reference to this on the Groovy site, books, etc.

How does this work, and more importantly, how do you discover this? Is there any XPath to GPath 'Rosetta Stone' out there?

+2  A: 

Well, as usual, the best place to find information is in the Groovy source itself.
The result of a parsing is a groovy.util.slurpersupport.GPathResult object.

If you look at the source (plain java file), you'll see that the getProperty(string) method has the following special operators:

  • ".." that returns the parent
  • "*" that returns all the children
  • "**" that act as a depth first loop
  • "@" that is used to access a property
  • the normal node accessor.

That's all, no other magic keywords for the moment.

gizmo
Excellent, thank you! I'd tried looking at the source but coudn't figure out where to look.
Dan Novak
A: 

To provide a little more information. All of those strings are treated as properties. None of them are actually operators. The calls are routed through GPathResult#getProperty which specifically checks for the operators listed in gizmo's answer.

noah