需要使用XmlParser将xml数据保存到文件时需要xml标记
问题描述:
将某些内容更新或添加到xml文件后,将移除xml声明。我正在使用XmlParser。这里是更新xml中的内容的代码。需要使用XmlParser将xml数据保存到文件时需要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)
更新顺利btw。更新后仅删除<?xml version="1.0" encoding="UTF-8"?>
问题。
答
以下是您可以做到的。致信@tim_yates。 只需注意最后一行。
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))
如果你想写在UTF-8?
new File(fileLocation).withWriter('UTF-8') { writer ->
writer.write(groovy.xml.XmlUtil.serialize(xml))
}
试过'XmlUtil.serialize(xml)'? –
@tim_yates是的。更新了代码仍然不起作用 – ayZagen
@ayZagen,你的意思是说蒂姆的建议工作,对吧? – Rao