This project is archived and is in readonly mode.

#1598 open
Peter Wagenet

Preserve XML Attributes with Hash#from_xml and ActiveResource

Reported by Peter Wagenet | December 18th, 2008 @ 06:28 PM | in 3.x

Currently, Hash#to_xml and, by extension, ActiveResource ignore XML attributes in certain scenarios.

First, attributes are ignored on tags that have no children. For example:

Hash.from_xml("<tag attr='val'>content</tag>") #=> {"tag"=>"content"}

Unfortunately, in some instances, one does want to retain these attributes. This patch adds support for a second parameter for Hash.from_xml. This parameter, when set to true (default is false), preserves the attributes.

Hash.from_xml("<tag attr='val'>content</tag>", true) #=> {"tag"=>{"content"=>"content", "attr"=>"val"}}

The result is not quite as elegant, but is preferred to loss of data in some cases.

Furthermore, if the attribute is "type", Rails will by default attempt to typecast the content as such:

Hash.from_xml("<tag type='float'>1</tag>") #=> {"tag"=>1.0}

With the second parameter set to true, the normal behavior will still be retained where possible, but where no match can be found for the type, it will be passed through:

Hash.from_xml("<tag type='float'>1</tag>", true) #=> {"tag"=>1.0}
Hash.from_xml("<tag type='number'>1</tag>", true) #=> {"tag"=>{"type"=>"number", "content"=>"1"}}

More information about this problem and my solution is available in a writeup on my blog: Stop Hash.from_xml from Killing XML Attributes

Also included in this patch is a new format for ActiveResource called AttributePreservingXmlFormat in the event that you need ActiveResource to use the improved Hash.from_xml.

If anyone has a better idea about how to solve this problem, I'd love some feedback.

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

Tickets have moved to Github

The new ticket tracker is available at

Shared Ticket Bins