Groovy: Correct Syntax for XMLSlurper to find elements with a given attribute

泪湿孤枕 提交于 2019-12-05 20:54:15

问题


Given a HTML file with the structure html -> body -> a bunch of divs what is the correct groovy statement to find all of the divs with a non blank tags attribute?

The following is not working:

def nodes = html.body.div.findAll { it.@tags != null }

because it finds all the nodes.


回答1:


Try the following (Groovy 1.5.6):

def doc = """
<html>
    <body>
        <div tags="1">test1</div>
        <div>test2</div>
        <div tags="">test3</div>
        <div tags="4">test4</div>
    </body>
</html>
"""

def html = new XmlSlurper().parseText( doc)

html.body.div.findAll { it.@tags.text()}.each { div ->
    println div.text()
}

This outputs:

test1
test4


来源:https://stackoverflow.com/questions/100325/groovy-correct-syntax-for-xmlslurper-to-find-elements-with-a-given-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!