After updating or adding something to an xml file, the xml declaration 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)
Updating is successful btw. Only the problem is <?xml version="1.0" encoding="UTF-8"?> removed after updating.
Here is what you can do to achieve the same. Credits to @tim_yates. Just note 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))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With