使用XmlParser将xml数据保存到文件时需要xml标记

时间:2017-04-18 14:59:07

标签: xml groovy xml-parsing

更新或向xml文件添加内容后,将删除xml声明。我正在使用 XmlParser 。以下是更新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"?>删除。

1 个答案:

答案 0 :(得分:1)

您可以采取以下措施来实现相同目标。积分给@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))
}