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

前端之家收集整理的这篇文章主要介绍了如何使用Parser实例将XML写入文件?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我的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)
如果您更换会发生什么:
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>

猜你在找的XML相关文章