2017-04-18 103 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