title: Pretty-print to file with REXML
body: <p>I am having trouble editing an XML file correctly. I want to remove certain elements and then add new ones.</p>
  
  <pre><code>&lt;project&gt;
      &lt;option&gt;
          &lt;name&gt;foo&lt;/name&gt;
          &lt;state&gt;0&lt;/state&gt;
      &lt;/option&gt;
      &lt;option&gt;
          &lt;name&gt;bar&lt;/name&gt;
          &lt;state&gt;foo/apple&lt;/state&gt;
          &lt;state&gt;foo/orange&lt;/state&gt;
      &lt;/option&gt;
  &lt;/project&gt;
  </code></pre>
  
  <p>I want to remove the <code>state</code>s apple and orange and insert grape, lemon and lime. I have tried with this code:</p>
  
  <pre><code>#!/usr/bin/ruby -w
  require 'fileutils'
  require 'rexml/document'
  require 'find'
  include REXML
  
  path = 'C:\Users\GustavWi\Documents\Gustav\help.xml'
  xmlfile = File.new(path)
  xmldoc = Document.new(xmlfile)
  str_new_elements =["grape","lemon","lime"]
  xmldoc.elements.each("project/option") do |parent| 
      if parent.elements['name'].text == 'bar'
          parent.elements.each do |element|
          str = element.text.split('/')
              if str[0] == 'foo'
              parent.delete_element(element)
              end
          end
          str_new_elements.each do |dir|
              state = Element.new("state")
              state.text = dir
              parent.add_element(state)
          end
      end
  end
  
  File.open(path,"w") do |data|
          xmldoc.write(data)
  end
  </code></pre>
  
  <p>The problem is that the output is:</p>
  
  <pre><code>&lt;project&gt;
      &lt;option&gt;
          &lt;name&gt;foo&lt;/name&gt;
          &lt;state&gt;0&lt;/state&gt;
      &lt;/option&gt;
      &lt;option&gt;
          &lt;name&gt;bar&lt;/name&gt;
  
  
      &lt;state&gt;grape&lt;/state&gt;&lt;state&gt;lemon&lt;/state&gt;&lt;state&gt;lime&lt;/state&gt;&lt;/option&gt;
  &lt;/project&gt;
  </code></pre>
  
  <p>The problem is the empty lines and the missing indentation of the new elements.</p>
  
  <p>I am using Ruby 1.8.6 so that might be a problem but I have not seen any info that this is a problem in 1.8.6.</p>
  
  <p>Almost the same problem can be seen in the book "Programming Ruby The Pragmatic Programmers' Guide" on page 726.</p>