0

给定以下 HTML 片段,我需要为属性等于的meta标签和属性name等于descriptionmeta标签property提取内容属性的文本og:title。我已经尝试过Groovy: Correct Syntax for XMLSlurper to find elements with a given attribute中显示的内容,但它在 Groovy 1.8.6 中似乎不一样。

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://ogp.me/ns/fb#">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=8" />
    <meta property="fb:admins" content="100003979125336" />
    <meta name="description" content="Shiny embossed blue butterfly" />
    <meta name="keywords" content="Fancy That Blue Butterfly Platter" />
    <meta property="og:title" content="Fancy That Blue Butterfly Platter" />

有没有一种干净的方法来用 GPath 检索这些?

4

1 回答 1

0

这适用于 groovy 2.0.1 - 我目前手头没有 1.8.6:

def slurper = new XmlSlurper()
File xmlFile = new File('sample.xml')
def xml = slurper.parseText(xmlFile.text)
println 'description = ' + xml.head.children().find{it.name() == 'meta' && it.@name == 'description'}.@content
println 'og:title = ' + xml.head.children().find{it.name() == 'meta' && it.@property == 'og:title'}.@content
于 2012-09-07T02:27:43.460 回答