I want to convert my XML document to Hash in Ruby/Rails. Actually, the default conversion by Hash.from_xml in Rails works for me except in one case.
I have a list of items contained in <item-list>
element, these items can be of different types though. For instance, standard-item
and special-item
, each of which has different set of child elements.
<item-list>
<standard-item>
<foo>...</foo>
<bar>...</bar>
</standard-item>
<standard-item>
<foo>...</foo>
<bar>...</bar>
</special-item>
<special-item>
<baz>...</baz>
</special-item>
</item-list>
This XML structure can be confusing for Hash.from_xml as it does not know that both standard-item and special-item are both items and should be in the same level. Hence, from the above XML, the hash generated by Hash.from_xml will be:
{ 'item-list' => { 'standard-item' => [ { 'foo' => '...', 'bar' => '...' },
{ 'foo' => '...', 'bar' => '...' } ],
'special-item' => { 'baz' => '...' } }}
But what I want is to have all items as list members, like this:
{ 'item-list' => [ { 'standard-item' => { 'foo' => '...', 'bar' => '...' } },
{ 'standard-item' => { 'foo' => '...', 'bar' => '...' } },
{ 'special-item' => { 'baz' => '...' } } ]
Is it possible to extend/customize from_xml so that it performs to way I want to for this case? If it is not possible, what is the best way to achieve this? Given that this is the only element that contains something that deviates from general XML-to-Hash conversion, it does not seem right to me to implement the whole conversion routine where it might have already been implemented for a thousand times.
Another small note, Hash.to_xml
also replaces all dashes with underscores. Is there a way to prevent this replacement?