Say I want to output XML like this:
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
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
builder template. That gives us control over the order of the elements
But if that order isnâ€™t important, we can let Rails generate the XML for
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
certain attributes, but that can quickly get messy. If you have to
that meets a particular schema or DTD, youâ€™re probably better off
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.