开发者

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

开发者 https://www.devze.com 2022-12-18 06:50 出处:网络
While trying to parse RSS feeds in Groovy, I found a GPath example using wildcards: def text = \"\"\"

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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消