5

I have a gradle.build where I am trying to:

  1. read an XML file
  2. use XmlSlurper to update an attribute in the read XML file
  3. write the updated XML back to the originally parsed xml file.

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

What is the simplest way to write the modified XML to the originally parsed XML file?


My code so far:

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 to be file.xml so that it overwrites the original XML file.

Sled
  • 18,541
  • 27
  • 119
  • 168
Going Bananas
  • 2,265
  • 3
  • 43
  • 83

1 Answers1

12

What happens if you do:

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 )
}

Is it just not written? (seems to work for me)

tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • Hi @tim_yates, thanks for the quick reply. Your sample code works perfectly and it is a valid answer. My code is still not working however but it must be for another reason altogether (not exactly what that reason is yet but I am basically first exploding a zip and then, I am trying to update an xml file in the exploded archive. In my code I try to get to the xml file via a FileTree as I don't know the exact path to the file ahead of time). Anyway, I'll close this post for now as your answer pretty much answers my initial question! Thanks again, PM. – Going Bananas Aug 23 '13 at 09:22
  • @tim_yates what does the `.bind{ mkp.yield xml }` part do? – Sled Jan 10 '17 at 18:28
  • @ArtB I think it's a shortcut to http://docs.groovy-lang.org/latest/html/api/groovy/xml/MarkupBuilderHelper.html – slim Nov 16 '17 at 19:59