本文介绍了Groovy XmlSlurper解析混合文本和节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前正试图在包含混合文本和节点的文本中解析一个节点,并且我需要按照正确的顺序获取文本:
<?xml version =1.0encoding =UTF-8?>
< root>
< p>
文字有
< strong>节点< / strong>
需要解析
< / p>
< / root>
现在我想要解析它,以便获取整个文本,但仍然可以编辑节点。
在这个例子中,我需要结果:
文字有< b>节点< / b>它需要被解析
如果我只能得到<$ c $下所有元素的列表c> p 我可以测试它的节点或文本是否会很快乐, >解决方案
好的,我发现了一个解决方案,我可以使用没有任何(棘手)的解决方法。
事物是一个 NodeChild
没有一个Method,它既为您提供了子文本,也为子节点提供了一个 Node
的确如此。为了得到一个简单的使用 childNodes()
(因为slurper给你一个 NodeChild
)
def root = new XmlSlurper()。parse(xml)
root.childNodes()。each {target - > ($ s $ {
$ b $ for b
$ b $ s.text()
} else {
printlnText:+ s
}
}
}
这给了我结果:
Text:The文本有
节点:节点
文本:需要解析的文本
其中意味着当我们的节点仍然按照正确的顺序排列时,我可以轻松地做任何我想要的节点
I'm currently trying to parse a node in groovy which contains mixed text and nodes with text and I need to get the text in the right order for example:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<p>
The text has
<strong>nodes</strong>
which need to get parsed
</p>
</root>
Now I want it to parse so I get the whole text but can still edit the node.In this example I want the result:
The text has <b>nodes</b> which need to get parsed
If I could just get a list of all elements under the p
where I can test if its a node or text I would be happy, but I cant find any way to get that.
解决方案
ok, I found a solution I can use without any (tricky) workarounds.The thing ist, a NodeChild
doesn't have a Method that gives you both child text and child nodes but a Node
does. To get one simply use childNodes()
(because the slurper gives you a 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
}
}
}
This gives me the result:
Text: The text has
Node: nodes
Text: which need to get parsed
Which means I can easily do whatever I want with my Nodes while they are still in the right order with the text
这篇关于Groovy XmlSlurper解析混合文本和节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!