Groovy:Node.replaceNode 与 Node? [英] Groovy: Node.replaceNode with Node?

查看:35
本文介绍了Groovy:Node.replaceNode 与 Node?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想用 replaceNode 替换一个节点,但是,我不想使用 Builder 来完成它 - 或者更确切地说,我已经有了要替换它的节点:

Suppose I have a node I'd like to replace with replaceNode, however, I don't want to use a Builder to do it - or rather, I already have the node with which to replace it:

replacement = new XmlParser.parse('input.xml')
root.depthFirst().replaceme.each { it ->
  it.replaceNode { node ->
    // This is what I can't figure out
  }
}

我尝试了很多不同的迭代,但似乎无法解决.如果我只返回该段中的文本,它会将节点替换为空节点.

I've tried lots of different iterations, but can't seem to work it out. If I just return text in that segment, it replaces the node with an empty node.

例如,如果我的输入文件是这样的:这应该被替换

For example, if my input file is this: This should get replaced

我有一个这样的替代品:这将替换 Original

And I have a replacement like this: This will replace the Original

我想做这样的事情:

top = new XmlParser().parseFile('input.xml')
top.middle.each { it ->
  it.replaceNode { node ->
    new XmlParser().parseFile('replacement.xml')
  }
}

推荐答案

如果您不介意切换到 XmlSlurper(),以下应该可以工作:

If you don't mind switching to XmlSlurper() the following should work:

def top = new XmlSlurper().parse('input.xml')
top.middle.each { node ->
    node.replaceNode {
        mkp.yield(new XmlSlurper().parse('replacement.xml')) 
    }   
}

这会将所有中间节点替换为replacement.xml的内容

Which will replace all middle nodes with the contents of replacement.xml

这篇关于Groovy:Node.replaceNode 与 Node?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆