# To\_xml repeating elements and plain strings

**URL:** <https://www.ruby-forum.com/t/to-xml-repeating-elements-and-plain-strings/184777>\
**Category:** Rails\
**Created:** [March 8, 2010, 2:43pm UTC](https://www.ruby-forum.com/t/to-xml-repeating-elements-and-plain-strings/184777 "2010-03-08T14:43:49Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![harry-weeds](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/65b543/32.png) [@harry-weeds](https://www.ruby-forum.com/u/harry-weeds)\
**Post date:** [March 8, 2010, 2:43pm UTC](https://www.ruby-forum.com/t/to-xml-repeating-elements-and-plain-strings/184777/1 "2010-03-08T14:43:49Z")

</div>

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  
[Array to\_xml - Rails - Ruby-Forum](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?

---

<div class="post-metadata">

**Author:** ![harry-weeds](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/65b543/32.png) [@harry-weeds](https://www.ruby-forum.com/u/harry-weeds)\
**Post date:** [March 17, 2010, 12:40pm UTC](https://www.ruby-forum.com/t/to-xml-repeating-elements-and-plain-strings/184777/2 "2010-03-17T12:40:09Z")

</div>

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.
