I ended up parsing the nodes using libxml
and I am checking if the nodes has the signature I am looking for in order to figure out if I want to convert as an empty array vs. a nil value.
# Usage: Hash.from_xml_with_libxml(xml)
require 'xml/libxml'
# adapted from
# http://movesonrails.com/articles/2008/02/25/libxml-for-active-resource-2-0
class Hash
class << self
def from_xml_with_libxml(xml, strict=true)
LibXML::XML.default_load_external_dtd = false
LibXML::XML.default_pedantic_parser = strict
result = LibXML::XML::Parser.string(xml).parse
return { result.root.name.to_s => xml_node_to_hash_with_libxml(result.root)}
end
def xml_node_to_hash_with_libxml(node)
# If we are at the root of the document, start the hash
if node.element?
if node.children?
result_hash = {}
node.each_child do |child|
result = xml_node_to_hash_with_libxml(child)
if child.name == "text"
if !child.next? and !child.prev?
return result
end
elsif result_hash[child.name]
if result_hash[child.name].is_a?(Object::Array)
result_hash[child.name] << result
else
result_hash[child.name] = [result_hash[child.name]] << result
end
else
result_hash[child.name] = result
end
end
return result_hash
else
# Nodes of sort <audio_languages/>, are arrays,
# and nodes like <average_rating "nil"="true"/> are nil values.
if node.to_s.match(/^\<(.+)\/\>$/) && nil == node.attributes["nil"]
return []
end
return nil
end
else
return node.content.to_s
end
end
end
end