这是我的Groovy代码:
// ... def xml = new XmlParser().parse(fileName) xml.each { e -> // some changes are being made to XML xml.append("test","test me") } def writer = new FileWriter(newFileName) new XmlNodePrinter(new PrintWriter(writer)).print(xml)
代码可以工作,但输出XML有很多不必要的空格.看起来我写文件时做错了.
PS.感谢蒂姆,这是它应该如何工作(上面例子的最后一行将替换为这三行):
def printer = new XmlNodePrinter(new PrintWriter(writer)) printer.preserveWhitespace = true printer.print(xml)
如果您更换会发生什么:
原文链接:https://www.f2er.com/xml/292647.htmldef writer = new FileWriter(newFileName) new XmlNodePrinter(new PrintWriter(writer)).print(xml)
有:
new File( newFilename ).withWriter { out -> printer = new XmlNodePrinter( out ) printer.preserveWhitespace = true printer.print( xml ) }
– 编辑 –
正如所指出的,感觉它应该是preserveWhitespace = false,但是如果您尝试以下测试代码:
def x = """<langs type="current"> <language>Java</language> <language>Groovy</language> <language>JavaScript</language> </langs>""" def xml = new XmlParser().parseText( x ) xml.appendNode 'language','Ruby' def printIt = { node,pw -> println "With preserveWhitespace=$pw:" def s = new StringWriter() printer = new XmlNodePrinter( new PrintWriter( s ) ) printer.preserveWhitespace = pw printer.print( xml ) println s } printIt xml,true printIt xml,false
你得到输出:
With preserveWhitespace=true: <langs type="current"> <language>Java</language> <language>Groovy</language> <language>JavaScript</language> <language>Ruby</language> </langs> With preserveWhitespace=false: <langs type="current"> <language> Java </language> <language> Groovy </language> <language> JavaScript </language> <language> Ruby </language> </langs>