2017-04-18 9 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) 

更新が成功しました。更新後に問題が発生したのは<?xml version="1.0" encoding="UTF-8"?>です。

+3

試した 'XmlUtil.serialize(xml)'? –

+0

@tim_yatesはい。まだ動作していないコードを更新しました – ayZagen

+0

@ayZagen、あなたはtimの提案がうまくいったと言っていますか? – 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

例:this [link](http://prnt.sc/exwnk6)は[link](http://prnt.sc/exwnr5)になります – ayZagen

関連する問題