我目前正在尝试解析 groovy 中的一个节点,其中包含混合文本和带有文本的节点,我需要以正确的顺序获取文本,例如:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<p>
The text has
<strong>nodes</strong>
which need to get parsed
</p>
</root>
现在我希望它能够解析,这样我就可以获得整个文本,但仍然可以编辑节点。 在此示例中,我想要结果:
The text has <b>nodes</b> which need to get parsed
如果我能获得 p
下所有元素的列表,我可以在其中测试它是否是节点或文本,我会很高兴,但我找不到任何方法来获得它。
最佳答案
好的,我找到了一个可以使用的解决方案,无需任何(棘手的)解决方法。
问题是,NodeChild
没有提供子文本和子节点的方法,但 Node
有。要获得一个,只需使用 childNodes()
(因为 slurper 为您提供一个 NodeChild
)
def root = new XmlSlurper().parse(xml)
root.childNodes().each { target ->
for (s in target.children()) {
if (s instanceof groovy.util.slurpersupport.Node) {
println "Node: "+ s.text()
} else {
println "Text: "+ s
}
}
}
这给了我结果:
Text: The text has
Node: nodes
Text: which need to get parsed
这意味着我可以轻松地对我的节点执行任何我想要的操作,同时它们仍然与文本保持正确的顺序
关于xml - Groovy XmlSlurper 解析混合文本和节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25135812/