2015-07-10 34 views
1

我發現一些有用的XML處理代碼在這裏: http://www.groovy-lang.org/processing-xml.htmlGroovy語法 - 什麼是'**'xml method-like-thingy?

它提供了以下有用的例子:

def response = new XmlSlurper().parseText(books) 
def titles = response.'**'.findAll{ node-> node.name() == 'title' }*.text() 

我得到的,它是一個外卡約定,但究竟怎樣的「** '字符串指示findAll方法來搜索每個節點?其他什麼字符串會做有用的事情?這是記錄在某處嗎?

回答

1

這是depthFirst()的快捷方式。請參閱API文檔GPathResult#getProperty(String)

返回此GPathResult的指定屬性。

。實現如下快捷鍵:

'..' for parent() 
'*' for children() 
'**' for depthFirst() 
'@' for attribute access 

有關的getProperty是怎麼做的,這裏是從GPathResult代碼:

public Object getProperty(final String property) { 
    if ("..".equals(property)) { 
     return parent(); 
    } else if ("*".equals(property)) { 
     return children(); 
    } else if ("**".equals(property)) { 
     return depthFirst(); 
    } else if (property.startsWith("@")) { 
     if (property.indexOf(":") != -1) { 
      final int i = property.indexOf(":"); 
      return new Attributes(this, "@" + property.substring(i + 1), property.substring(1, i), this.namespaceTagHints); 
     } else { 
      return new Attributes(this, property, this.namespaceTagHints); 
     } 
    } else { 
     if (property.indexOf(":") != -1) { 
      final int i = property.indexOf(":"); 
      return new NodeChildren(this, property.substring(i + 1), property.substring(0, i), this.namespaceTagHints); 
     } else { 
      return new NodeChildren(this, property, this.namespaceTagHints); 
     } 
    } 
} 

我一直期待使用的是看某種元編程兩輪牛車的missingProperty或某物,但這不是必需的。對response.'**'的調用被視爲訪問一個屬性,並以「**」作爲參數調用getProperty。

+0

有沒有兩輪牛車,這只是一個財產是不是? –

+0

@tim_yates:是的,它只是一個屬性,不得不審查屬性如何工作。 –