2017-04-18 1 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, 팀의 제안이 효과가 있었다고 말하는 것입니까? – 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

관련 문제