使用 XmlSlurper 返回的 GPathResult 迭代具有给定名称的所有子项
我已经使用 XmlSlurper 解析了一些 html。现在我想迭代具有给定元素名称的所有子元素。
我现在得到的是以下代码片段,
html.'**'.findAll { it.name() == 'a' }.each {
println it
}
它可以工作,但还不够好。我想简单地写这样的东西
html.'**'.a.each {
println it
}
如果我这样做,GPath 会抱怨没有名称为“a”的属性。知道是否有简单的语法来制定此迭代?
I've parsed some html using XmlSlurper. Now I want to iterate all the children with a given element name.
What I've got now is the following code snippet
html.'**'.findAll { it.name() == 'a' }.each {
println it
}
It works but just isn't groovy enough. I would like to simply write something like this
html.'**'.a.each {
println it
}
If I do it this way, GPath complains that there is no property with name 'a'. Any idea if there is an easy syntax to formulate this iteration?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用递归闭包:
Use recursive closure:
不幸的是,目前 Groovy 中无法执行您所要求的操作。
当您对 GPathResult(或其任何子项)执行此类操作时,
所做的是针对每个“.”。调用 GPathResult.getProperty() 方法已完成。而这个方法只有几个有效的语法糖(*、**、..和@)。这意味着,如果您不使用其中之一,它会假设您所定位的每个节点确实存在该属性。
如果您希望有一个条件空安全运算符来遍历您的树,它将请求在 GPathResult 类中添加语法糖前缀(例如“?a”)。也许您可以使用 Expando 元类并重写 getProperty 方法来实现这一点,但我没有尝试。
Unfortunately, there is currently no way in Groovy to perform what you're asking.
When you perform such operation on a GPathResult (or any of its children)
What is done is that for each "." a call to the GPathResult.getProperty() method is made. And this method as only a few valid syntactic sugar (*, **, .. and @). This means that if you don't use one of them, it assume that the property really exist for each node you're targeting.
If you would like to have a conditional null-safe operator for traversing your tree, it would request either the addition of a syntactic sugar prefix (e.g. "?a" ) in the GPathResult class. Maybe that you can achieve that using the expando metaclass and overriding the getProperty method, but I did not try it.