如何解析 Groovy 中的 XML 条评论?

How to parse XML comments in Groovy?

有什么方法可以解析 Groovy 中的 XML 评论吗?

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

假设以下文件 (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)

输出文件,看不到注释

只要你有 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()