作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在编写一个 HTML 解析器,它使用 TagSoup 将格式良好的结构传递给 XMLSlurper。
这是通用代码:
def htmlText = """
<html>
<body>
<div id="divId" class="divclass">
<h2>Heading 2</h2>
<ol>
<li><h3><a class="box" href="#href1">href1 link text</a> <span>extra stuff</span></h3><address>Here is the address<span>Telephone number: <strong>telephone</strong></span></address></li>
<li><h3><a class="box" href="#href2">href2 link text</a> <span>extra stuff</span></h3><address>Here is another address<span>Another telephone: <strong>0845 1111111</strong></span></address></li>
</ol>
</div>
</body>
</html>
"""
def html = new XmlSlurper(new org.ccil.cowan.tagsoup.Parser()).parseText( htmlText );
html.'**'.grep { it.@class == 'divclass' }.ol.li.each { linkItem ->
def link = linkItem.h3.a.@href
def address = linkItem.address.text()
println "$link: $address\n"
}
我希望 each 让我依次选择每个“li”,这样我就可以检索相应的 href 和地址详细信息。相反,我得到了这个输出:
#href1#href2: Here is the addressTelephone number: telephoneHere is another addressAnother telephone: 0845 1111111
我已经检查了网络上的各种示例,这些示例要么处理 XML,要么是单行示例,如“从该文件中检索所有链接”。 it.h3.a.@href 表达式似乎正在收集文本中的所有 href,即使我将它传递给父“li”节点的引用也是如此。
你能告诉我吗:
谢谢。
最佳答案
用查找替换grep:
html.'**'.find { it.@class == 'divclass' }.ol.li.each { linkItem ->
def link = linkItem.h3.a.@href
def address = linkItem.address.text()
println "$link: $address\n"
}
然后你会得到
#href1: Here is the addressTelephone number: telephone
#href2: Here is another addressAnother telephone: 0845 1111111
grep 返回一个 ArrayList 但 find 返回一个 NodeChild 类:
println html.'**'.grep { it.@class == 'divclass' }.getClass()
println html.'**'.find { it.@class == 'divclass' }.getClass()
结果:
class java.util.ArrayList
class groovy.util.slurpersupport.NodeChild
因此,如果你想使用 grep,你可以像这样嵌套另一个 each 以使其工作
html.'**'.grep { it.@class == 'divclass' }.ol.li.each {
it.each { linkItem ->
def link = linkItem.h3.a.@href
def address = linkItem.address.text()
println "$link: $address\n"
}
}
长话短说,在您的情况下,请使用 find 而不是 grep。
关于html - 使用 XmlSlurper : How to select sub-elements while iterating over a GPathResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1675542/
我是一名优秀的程序员,十分优秀!