在 Groovy 中加载、修改和编写 XML 文档

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2245641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 12:58:35  来源:igfitidea点击:

Load, modify, and write an XML document in Groovy

xmlgroovy

提问by Mike Sickler

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

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

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

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

回答by John Wagenleitner

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

您可以只修改节点的value属性来修改元素的值。

/* 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>
*/

回答by Heinrich Filter

If you want to use the XmlSlurper:

如果你想使用XmlSlurper

//Open file
def xml = new XmlSlurper().parse('/tmp/file.xml')

//Edit File e.g. append an element called foo with attribute bar
xml.appendNode {
   foo(bar: "bar value")
}

//Save File
def writer = new FileWriter('/tmp/file.xml')

//Option 1: Write XML all on one line
def builder = new StreamingMarkupBuilder()
writer << builder.bind {
  mkp.yield xml
}

//Option 2: Pretty print XML
XmlUtil.serialize(xml, writer)

Note: XmlUtilcan also be used with the XmlParseras used in @John Wagenleitner's example.

注意: XmlUtil也可以与XmlParser@John Wagenleitner 示例中使用的一样使用。

References:

参考:

回答by Dónal

There's a pretty exhaustive set of examples for reading/writing XML using Groovy here. Regarding the loading/saving the data to/from a file, the various methods/properties that Groovy adds to java.io.File, should provide the functionality you need. Examples include:

有读取/使用Groovy编写XML一个漂亮的一套详尽的例子在这里。关于向/从文件加载/保存数据,Groovy 添加到的各种方法/属性java.io.File应该提供您需要的功能。例子包括:

File.write(text)
File.text
File.withWriter(Closure closure) 

See herefor a complete list of these methods/properties.

有关这些方法/属性的完整列表,请参见此处

回答by Afrig Aminuddin

For the one who find the output empty, here is the solution:

对于发现输出为空的人,这是解决方案:

def xml = file("${projectDir}/src/main/AndroidManifest.xml")
def manifest = new XmlSlurper().parse(file(xml))
manifest.@package = "com.newapp.id"
xml.withWriter {out->
    XmlUtil.serialize(manifest, out)
}