使用 XmlSlurper 返回的 GPathResult 迭代具有给定名称的所有子项

发布于 2024-09-19 23:22:28 字数 394 浏览 4 评论 0原文

我已经使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

恬淡成诗 2024-09-26 23:22:33

使用递归闭包:

def out = new StringBuffer()

def printNode
printNode = { o,node ->         
    o << '<' + node.name()
    node.attributes().each{ o << ' ' + it.key + '="' + it.value + '"' }
    o << '>'
    node.children().each{ printNode(out,it) }
    o << '</' + node.name() + '>'  
}

html.'**'.findAll { it.name() == 'a' }.each { printNode(out,it) }

println out.toString()

Use recursive closure:

def out = new StringBuffer()

def printNode
printNode = { o,node ->         
    o << '<' + node.name()
    node.attributes().each{ o << ' ' + it.key + '="' + it.value + '"' }
    o << '>'
    node.children().each{ printNode(out,it) }
    o << '</' + node.name() + '>'  
}

html.'**'.findAll { it.name() == 'a' }.each { printNode(out,it) }

println out.toString()
懒猫 2024-09-26 23:22:32

不幸的是,目前 Groovy 中无法执行您所要求的操作。
当您对 GPathResult(或其任何子项)执行此类操作时,

html."**".a.b.c

所做的是针对每个“.”。调用 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)

html."**".a.b.c

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文