2017-04-18 49 views
3

将某些内容更新或添加到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"?>问题。

+3

试过'XmlUtil.serialize(xml)'? –

+0

@tim_yates是的。更新了代码仍然不起作用 – ayZagen

+0

@ayZagen,你的意思是说蒂姆的建议工作,对吧? – Rao

回答

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)) 
} 
+0

工作就像一个魅力。出于好奇,为什么它会在xml声明之后删除第一个空格呢?有没有办法保留它? – ayZagen

+0

没有找到你? – Rao

+0

for ex:this [link](http://prnt.sc/exwnk6)变成[link](http://prnt.sc/exwnr5) – ayZagen