Q:

Change a key from a number to a string using to_xml in rails?

If you have a hash:
{"0" => "value"}

And you turn it into XML:
{"0" => "value"}.to_xml

that returns:
<?xml version="1.0" encoding="UTF-8"?>
<hash>
  <0>value</0>
</hash>

This causes Chrome and many other XML parsers to choke, because the nodename is an integer. Does anyone have a clever / simple solution to fix this? I'm using respond_with and a hash, so extra points if I don't have to break that convention in my controller.

A:

You'll have to change the key/nodename to a non-numeric string to make it a valid XML element.
Assuming you can prefix the nodename with "Digit":
new_hash = {}
hash.each do  |k, v| 
  new_hash.merge!( k.gsub(/^\d/, "Digit#{k[0]}" ) => v ) 
end

new_hash.to_xml

See this for more details on xml nodes with integer names

