converting from xml name-values into simple hash

会有一股神秘感。 提交于 2019-11-28 09:20:39
ply

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").first

hash = node.element_children.each_with_object(Hash.new) do |e, h|
  h[e.name.to_sym] = e.content
end

puts 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.content
end

puts hash.inspect
# {:SessionID=>"FE5E27A056944FBFBEF047F2B99E0BF6",
#  :AccountNum=>"8228-5500", :AccountID=>"967454"}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!