2017-03-23 17 views
1

处理XML部分中的Groovy documentation提到breadthFirst()*的较短语法是同义的。然而,*使用最终只遍历父节点下一层:Groovy-XML Tree Traversal使用*作为语法糖的breadthFirst()方法

def books = '''\ 
<response> 
    <books> 
     <book available="20" id="1"> 
     <title>foo</title> 
     <author id="1">foo author</author> 
     </book> 
     <book available="14" id="2"> 
     <title>bar</title> 
     <author id="2">bar author</author> 
     </book> 
    </books> 
</response>''' 

def response = new XmlSlurper().parseText(books) 
def bk = response.'*'.find { node -> 
    node.name() == 'book' && node['@id'].toInteger() == 2 
} 
assert bk.empty 

而使用breadthFirst()明确做什么,我都期盼做这做广度优先遍历:

def books = '''\ 
<response> 
    <books> 
     <book available="20" id="1"> 
     <title>foo</title> 
     <author id="1">foo author</author> 
     </book> 
     <book available="14" id="2"> 
     <title>bar</title> 
     <author id="2">bar author</author> 
     </book> 
    </books> 
</response>''' 

def response = new XmlSlurper().parseText(books) 
def bk = response.breadthFirst().find { node -> 
    node.name() == 'book' && node['@id'].toInteger() == 2 
} 
assert bk.title == 'bar' // bk is no longer an empty list of children 

*语义明显不同于breadthFirst()。这是预期的行为,还是我错过了文档中的某些内容?

回答

1

我认为这个文档并没有强调*实际上是一个简写,它只能得到直接被调用的节点的子节点。从在写这篇文章的时候文档的例子是:作为你在自己的例子一样,他们没有使用response.'*'

def catcherInTheRye = response.value.books.'*'.find { node-> 
/* [email protected] == 2 could be expressed as node['@id'] == 2 */ 
    node.name() == 'book' && [email protected] == '2' 
} 

通知。所以*并非真的是breadthFirst()(我同意文档应审查)的简写。它仅仅意味着直接的孩子,而breadthFirst()递归地遍历节点。这可以从GPathResult.getProperty的Javadocs确认:

返回此GPathResult的指定属性。 。实现如下快捷键:

  • '..'parent()
  • '*'children()
  • '**'depthFirst()
  • '@'的属性访问

我创建this pull request来解决它。