Need xml markup when saving xml data to file using XmlParser

Once updated or added to XML, the xml declaration file is removed. I am using XmlParser . Here is the code to update something in the xml.

def xml = new XmlParser().parseText(new File(fileLocation).getText('UTF-8'))
def found = xml.myTag1.findAll()
found.each{
     it.mySubTag.value="Updated"
}

XmlUtil.serialize(xml)
def nodePrinter = new XmlNodePrinter(new PrintWriter(new File(fileLocation)))
nodePrinter.preserveWhitespace=true
nodePrinter.print(xml)

      

The update is good by the way. Only issue <?xml version="1.0" encoding="UTF-8"?>

removed after update.

+3


source to share


1 answer


Here's what you can do to achieve the same. Credits to @tim_yates. Just mark the last line.

def xml = new XmlParser().parseText(new File(fileLocation).getText('UTF-8'))
def found = xml.myTag1.findAll()
found.each{
     it.mySubTag.value="Updated"
}

//Write content of updated xml into file with xml declaration
new File(fileLocation).write(groovy.xml.XmlUtil.serialize(xml))

      



If you want to write in utf-8?

new File(fileLocation).withWriter('UTF-8') { writer ->
    writer.write(groovy.xml.XmlUtil.serialize(xml))
}

      

+1


source







All Articles