如何使用Parser实例将XML写入文件?

时间:2011-02-28 14:04:41

标签: xml groovy

这是我的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)

2 个答案:

答案 0 :(得分:12)

如果替换会发生什么:

def 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>

答案 1 :(得分:0)

我最终得到了这个模糊:

new File(myFilename).withWriter {
    def printer = new XmlNodePrinter(new PrintWriter(it))
    printer.preserveWhitespace = true
    printer.print(myXmlNode)
}