Writing updated XML to the originally parsed file

I have gradle.build where I try:

  • read xml file
  • use XmlSlurper to update an attribute in a read XML file
  • write the updated XML back to the originally parsed XML file.

The third step only works if I write modified XML to a new nonexistent XML file, but not to the originally parsed XML file.

What is the easiest way to write modified XML to an initially parsed XML file?


My code is:

 def inFile = file('file.xml') def outFile = file('_file.xml') def xml = new XmlSlurper().parse(inFile) // update xml code here def outBuilder = new StreamingMarkupBuilder() def outWriter = outFile.newWriter() XmlUtil.serialize(outBuilder.bind{ mkp.yield xml }, outWriter) 

I would like outFile be file.xml so that it overwrites the original XML file.

+4
source share
1 answer

What happens if you run:

 def inFile = file( 'file.xml' ) def xml = new XmlSlurper().parse( inFile ) xml.appendNode { haha( 'tim_yates' ) } inFile.withWriter { outWriter -> XmlUtil.serialize( new StreamingMarkupBuilder().bind{ mkp.yield xml }, outWriter ) } 

Isn't it just written? (seems to work for me)

+8
source

Source: https://habr.com/ru/post/1498420/


All Articles