开发者

How to write an XML to file, with just a Parser instance?

This is my Groovy code:

// ...
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)

The code works, but the output XML has a lot of unnecessary white spaces. Looks like I'm do开发者_JS百科ing something wrong with writing to file.

ps. Thanks to Tim, this is how it should work (the last line of the example above shall be replaced with these three lines):

def printer = new XmlNodePrinter(new PrintWriter(writer))
printer.preserveWhitespace = true
printer.print(xml)


What happens if you replace:

def writer = new FileWriter(newFileName)
new XmlNodePrinter(new PrintWriter(writer)).print(xml)

with:

new File( newFilename ).withWriter { out ->
  printer = new XmlNodePrinter( out )
  printer.preserveWhitespace = true
  printer.print( xml )
}

-- edit --

As pointed out, it feels like it should be preserveWhitespace = false, however if you try the following test code:

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

You get the output:

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>


I ended up with this blurb:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜