REXML Formatter issue - does each Element need formatting?


Recently upgraded to Ruby 1.8.6 and having some backwards-compatibility
problems with REXML given it’s new formatting setup.

Basically, I have a XML document with three elements underneath the
root. After I completely generate the XML, I use the following code to
pretty-print it out:

formatter ="#{@file_path}", 'w') do |f|
  formatter.write(@document, f)

What appears to happen, however, is that only the first subordinate
element is pretty - printed, and the rest of the contents of the root
element are printed on one line after the first element ends.

It currently looks like this:

…pretty-printed contents of first_elem…
</first_elem><second_elem>…inline contents of
second_elem…</second_elem><third_elem>…inline contents of

The consumer of this XML is unable to parse this. Changing the consumer
is not possible at this point, so I need to fix how this is output.

What I want to see is:

…pretty-printed contents of first_elem…
…pretty-printed contents of second_elem…
…pretty-printed contents of third_elem…

My guess is that I will need to write out each element separately with a
formatter, since the formatting of the document that I invoked doesn’t
appear to propagate down into each element.

Am I on the right track?


Actually, it is more involved than that.

I have a XML template with the following:

…contents of first_elem…

I then read in this XML and dynamically add in second_elem and
third_elem as siblings to first_elem. Using the default formatter
prints them all inline. Using the pretty printer prints each element
tag (both open and close) and the value on a separate line.

I want something in between these two extremes.

I want to print out the contents of <second_elem> and <third_elem> like


Does anyone know how to create a custom formatter for correctly provide
formatting directives to REXML?



It turns out that the REXML pretty formatter has a “compact” flag that
is undocumented, but does exactly what I want.

So this code…

require ‘rexml/document’
require ‘rexml/formatters/pretty’

def write()
formatter =
formatter.compact = true"#{@file_path}", ‘w’) do |f|
formatter.write(@document, f)

seems to work well (note the “formatter.compact = true” line).


Wes G. [email protected] wrote:

seems to work well (note the “formatter.compact = true” line).

thanks a lot, i had the same prob :wink:
clearly i don’t understand why this isn’t the default printing mode for

because having :
#the text for “a_node”

adds to #text nodes (ie “\n”) …

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs