0

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.

RandallB
  • 5,415
  • 6
  • 34
  • 47

1 Answers1

1

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

Community
  • 1
  • 1
roob
  • 1,116
  • 7
  • 11
  • Seems like the regex is the way to go. I'll probably just do that in the generated xml since it'll be simpler that way, and create a new action specifically to do this. Thanks! – RandallB Dec 10 '14 at 17:34