To_xml repeating elements and plain strings

Say I want to output XML like this:

123 apple banana pear lemon

Is there a way of doing that with to_xml?

It seems like there’s two problems: to_xml always creates a wrapping
element when it encounters an array, and…

You can put plain strings into hash values and it works, but plain
strings in arrays doesn’t work. That’s this guy’s problem again
http://www.ruby-forum.com/topic/167577 .

Maybe I should look at using Builder instead. Seems it gives me power
over the XML output, but my code builds up a nested hash/array
structure. Dont I end up embedding knowledge of that structure in two
different places. Also from my hash I wanted to generate JSON too. Is
there an approach converting from an XML doc object to JSON? or some
other way I should be thinking about this?

I noticed some sections in the “Agile Web Developement with Rails” book:

"
Autogenerating the XML
In the previous examples, we generated the XML responses by hand, using
the
builder template. That gives us control over the order of the elements
returned.
But if that order isn’t important, we can let Rails generate the XML for
a model
object for us by calling the model’s to_xml method.

Note that by default to_xml dumps everything out. You can tell it to
exclude
certain attributes, but that can quickly get messy. If you have to
generate XML
that meets a particular schema or DTD, you’re probably better off
sticking with
builder templates.
"

So that confirms what I’m finding, that to_xml isn’t too great for tight
control of your output. Builder is better. But does anyone know of a
best-of-both-worlds approach? I want JSON as an alternate output, so it
seems to make sense to create a hash structure mirroring the desired
output structure, but then for the XML I’d need to unpack and re-pack
the same structure within my builder definition.

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