2015-07-10 35 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:是的,它只是一个属性,不得不审查属性如何工作。 –