Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on Feb 28th, 2012  |  syntax: None  |  size: 1.92 KB  |  views: 8  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. # USAGE: Hash.from_xml:(YOUR_XML_STRING)
  2. require 'nokogiri'
  3. # modified from http://stackoverflow.com/questions/1230741/convert-a-nokogiri-document-to-a-ruby-hash/1231297#1231297
  4.  
  5. class Hash
  6.   class << self
  7.     def from_xml(xml_io)
  8.       begin
  9.         result = Nokogiri::XML(xml_io)
  10.         return { result.root.name.to_sym => xml_node_to_hash(result.root)}
  11.       rescue Exception => e
  12.         # raise your custom exception here
  13.       end
  14.     end
  15.  
  16.     def xml_node_to_hash(node)
  17.       # If we are at the root of the document, start the hash
  18.       if node.element?
  19.         result_hash = {}
  20.         if node.attributes != {}
  21.           result_hash[:attributes] = {}
  22.           node.attributes.keys.each do |key|
  23.             result_hash[:attributes][node.attributes[key].name.to_sym] = prepare(node.attributes[key].value)
  24.           end
  25.         end
  26.         if node.children.size > 0
  27.           node.children.each do |child|
  28.             result = xml_node_to_hash(child)
  29.  
  30.             if child.name == "text"
  31.               unless child.next_sibling || child.previous_sibling
  32.                 return prepare(result)
  33.               end
  34.  
  35.             elsif child.name == '#cdata-section'
  36.               return prepare(child.content)
  37.  
  38.             elsif result_hash[child.name.to_sym]
  39.               if result_hash[child.name.to_sym].is_a?(Object::Array)
  40.                 result_hash[child.name.to_sym] << prepare(result)
  41.               else
  42.                 result_hash[child.name.to_sym] = [result_hash[child.name.to_sym]] << prepare(result)
  43.               end
  44.  
  45.             else
  46.               result_hash[child.name.to_sym] = prepare(result)
  47.             end
  48.           end
  49.         end
  50.  
  51.         result_hash
  52.       else
  53.         return prepare(node.content.to_s)
  54.       end
  55.     end
  56.  
  57.     def prepare(data)
  58.       (data.class == String && data.to_i.to_s == data) ? data.to_i : data
  59.     end
  60.   end
  61.  
  62.   def to_struct(struct_name)
  63.       Struct.new(struct_name,*keys).new(*values)
  64.   end
  65. end