在 Groovy 中加载、修改和编写 XML 文档 [英] Load, modify, and write an XML document in Groovy

查看:20
本文介绍了在 Groovy 中加载、修改和编写 XML 文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 XML 文档,我想从文件中加载它,修改一些特定的元素,然后写回磁盘.

I have an XML document that I want to load from a file, modify a few specific elements, and then write back to disk.

我在 Groovy 中找不到任何有关如何执行此操作的示例.

I can't find any examples of how to do this in Groovy.

推荐答案

你可以只修改节点的 value 属性来修改元素的值.

You can just modify the node's value property to modify the values of elements.

/* input:
<root>
  <foo>
    <bar id="test">
      test
    </bar>
    <baz id="test">
      test
    </baz>
  </foo>
</root>
*/

def xmlFile = "/tmp/test.xml"
def xml = new XmlParser().parse(xmlFile)
xml.foo[0].each { 
    it.@id = "test2"
    it.value = "test2"
}
new XmlNodePrinter(new PrintWriter(new FileWriter(xmlFile))).print(xml)

/* output:
<root>
  <foo>
    <bar id="test2">
      test2
    </bar>
    <baz id="test2">
      test2
    </baz>
  </foo>
</root>
*/

这篇关于在 Groovy 中加载、修改和编写 XML 文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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