Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need xml markup on persisting xml data to file using XmlParser

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.

like image 216
ayZagen Avatar asked Apr 16 '26 10:04

ayZagen


1 Answers

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))
}
like image 156
Rao Avatar answered Apr 19 '26 01:04

Rao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!