views:

882

answers:

2

Given my existing XML (test.xml):

<root>
  <element>
    <child id="1" />
    <child id="2" />
    <child id="3" />
  </element>
</root>

And my ruby code:

require 'rubygems'
require 'xml'

parser = XML::Parser.file("test.xml")
doc = parser.parse

target = doc.find('/*/element')
target << child = XML::Node.new('child')
child['id'] = '4'

XML.indent_tree_output = true
doc.save(filename, :indent => true, :encoding => XML::Encoding::UTF_8)

My problem is that it formats the output like this:

<root>
  <element>
    <child id="1" />
    <child id="2" />
    <child id="3" />
  <child id="4" /></element>
</root>

... with subsequent additions looking like this:

<root>
  <element>
    <child id="1" />
    <child id="2" />
    <child id="3" />
  <child id="4" /><child id="5" /><child id="6" /></element>
</root>

What I WANT is this:

<root>
  <element>
    <child id="1" />
    <child id="2" />
    <child id="3" />
    <child id="4" />
    <child id="5" />
    <child id="6" />
  </element>
</root>

... but how do I get it?

A: 

If you're using document.save then make sure you set indent to true, also make sure XML.indent_tree_output is set. Something like this:

XML.indent_tree_output = true
doc.save(filename, :indent => true, :encoding => XML::Encoding::UTF_8)

Rubyforge isn't working for me so I can't verify it in the documentation, but I think both need to be set to true for indenting and new lines to work.

Firas Assaad
Forgot to add that line into my question, but it was there in my original file and I still had the issue. "test.xml" is originally created from scratch by another section of my code; I'm just having issues adding nodes into an existing file. Rubyforge isn't working for me either...
neezer
+1  A: 

replace
parser = XML::Parser.file("test.xml")

with
parser = XML::Parser.file("test.xml", :options => XML::Parser::Options::NOBLANKS )

that's help