converting from xml name-values into simple hash converting from xml name-values into simple hash xml xml

converting from xml name-values into simple hash


There are a few libraries you can use in Ruby to do this.

Ruby toolbox has some good coverage of a few of them:

https://www.ruby-toolbox.com/categories/xml_mapping

I use XMLSimple, just require the gem then load in your xml file using xml_in:

require 'xmlsimple'hash = XmlSimple.xml_in('session.xml')

If you're in a Rails environment, you can just use Active Support:

require 'active_support' session = Hash.from_xml('session.xml')


Using Nokogiri to parse the XML with namespaces:

require 'nokogiri'dom = Nokogiri::XML(File.read('OX.session.xml'))node = dom.xpath('ox:CAppLogin',                 'ox' => "http://oxbranch.optionsxpress.com").firsthash = node.element_children.each_with_object(Hash.new) do |e, h|  h[e.name.to_sym] = e.contentendputs hash.inspect# {:SessionID=>"FE5E27A056944FBFBEF047F2B99E0BF6",#  :AccountNum=>"8228-5500", :AccountID=>"967454"}

If you know that the CAppLogin is the root element, you can simplify a bit:

require 'nokogiri'dom = Nokogiri::XML(File.read('OX.session.xml'))hash = dom.root.element_children.each_with_object(Hash.new) do |e, h|  h[e.name.to_sym] = e.contentendputs hash.inspect# {:SessionID=>"FE5E27A056944FBFBEF047F2B99E0BF6",#  :AccountNum=>"8228-5500", :AccountID=>"967454"}