formatting output of Builder#to_xml

473 views
Skip to first unread message

Will Rogers

unread,
Feb 25, 2010, 2:51:29 PM2/25/10
to nokogiri-talk
I have some code that takes an existing XML document and adds an
element to it using Nokogiri::XML::Builder. It looks something like
this:

original = Nokogiri::XML(super)
builder = Nokogiri::XML::Builder.with(original.at 'application') do |
xml|
xml.module {
xml.connector 'blahblahblah'
}
end
builder.to_xml

The resulting string is correct, but it is not "pretty printed," i.e.
the added element is all on one line and not indented with the rest of
the document. I have tried various arguments to to_xml
including :indent and :save_with but they don't seem to have any
effect on the output. Am I overlooking something? How can I get it to
format the output nicely?

Aaron Patterson

unread,
Feb 25, 2010, 4:12:14 PM2/25/10
to nokogi...@googlegroups.com
On Thu, Feb 25, 2010 at 1:11 PM, Aaron Patterson
<aaron.p...@gmail.com> wrote:
> Hi Roger,

Oops, I meant "Hi Will". Sorry, I'm really tired. :-(

--
Aaron Patterson
http://tenderlovemaking.com/

Aaron Patterson

unread,
Feb 25, 2010, 4:11:28 PM2/25/10
to nokogi...@googlegroups.com
Hi Roger,

In XML, whitespace can be considered meaningful. If you parse a
document that contains whitespace nodes, libxml2 will assume that
whitespace nodes are meaningful and will not insert them for you.

You can tell libxml2 that whitespace is not meaningful by passing the
"noblanks" flag to the parser. To demonstrate, here is an example
that reproduces your error, then does what you want:

require 'nokogiri'


def build_from node
builder = Nokogiri::XML::Builder.with(node) do |xml|
xml.hello do
xml.world
end
end
end

xml = DATA.read
doc = Nokogiri::XML(xml)
puts build_from(doc.at('bar')).to_xml

doc = Nokogiri::XML(xml) { |x| x.noblanks }
puts build_from(doc.at('bar')).to_xml

__END__
<root>
<foo>
<bar>
<baz />
</bar>
</foo>
</root>

Hope that helps!

Will Rogers

unread,
Feb 25, 2010, 4:40:29 PM2/25/10
to nokogi...@googlegroups.com
On Thu, Feb 25, 2010 at 4:11 PM, Aaron Patterson
<aaron.p...@gmail.com> wrote:
> You can tell libxml2 that whitespace is not meaningful by passing the
> "noblanks" flag to the parser.  To demonstrate, here is an example
>
>    doc = Nokogiri::XML(xml) { |x| x.noblanks }

Thank you, Aaron. That makes sense!


-- Will

Reply all
Reply to author
Forward
0 new messages