【问题标题】:How to parse XML comments in Groovy?如何在 Groovy 中解析 XML 注释?
【发布时间】:2018-07-17 10:47:41
【问题描述】:

有什么方法可以在 Groovy 中解析 XML cmets?

XMLParser 和 XMLSluprer 似乎都不支持 cmets 节点。

假设以下文件(example.html):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>title</title>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">title</td></tr>
</thead><tbody>
<!--I cannot be seen-->
<tr>
	<td>x</td>
	<td>x</td>
	<td>x</td>
</tr>
</tbody></table>
</body>
</html>

这是我的代码:

def parser = new XmlSlurper(false, false)
parser.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false)
parser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false)

def response = parser.parse('example.html')

当我使用时

println XmlUtil.serialize(response)

输出文件,看不到注释。

【问题讨论】:

  • 在使用 groovy 解析器时无法获取 cmets。但你可以使用 DOM 或其他 xml 模型来获取 cmets。

标签: xml groovy xml-parsing xmlslurper


【解决方案1】:

只要你有 html - 就可以使用 jsoup 来解析

@Grab(group='org.jsoup', module='jsoup', version='1.11.3')
import org.jsoup.Jsoup
import org.jsoup.nodes.Document

def html = '''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>title</title>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">title</td></tr>
</thead><tbody>
<!--I cannot be seen-->
<tr>
    <td>x</td>
    <td>x</td>
    <td>x</td>
</tr>
</tbody></table>
</body>
</html>'''

Document doc = Jsoup.parse(html)
println doc.select('html body table tbody').first()?.childNodes()?.find{it.nodeName()=='#comment'}?.getData()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 2023-04-05
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    相关资源
    最近更新 更多