Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the full syntax of Groovy's GPath expressions?

Tags:

groovy

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?

like image 593
Dan Novak Avatar asked Jan 22 '10 14:01

Dan Novak


2 Answers

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.

like image 100
gizmo Avatar answered Sep 17 '22 18:09

gizmo


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.

like image 39
noah Avatar answered Sep 17 '22 18:09

noah