从xml名称值转换为简单哈希

时间:2012-06-21 13:52:04

标签: ruby xml yaml rexml

我不知道这是什么名字,这使我的搜索变得复杂。

我的数据文件 OX.session.xml 采用(旧?)格式

<?xml version="1.0" encoding="utf-8"?>
<CAppLogin xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://oxbranch.optionsxpress.com">
  <SessionID>FE5E27A056944FBFBEF047F2B99E0BF6</SessionID>
  <AccountNum>8228-5500</AccountNum>
  <AccountID>967454</AccountID>
</CAppLogin>

究竟是什么称为XML数据格式?

无论如何,我想要的是在我的Ruby代码中最终得到一个哈希:

CAppLogin = { :SessionID => "FE5E27A056944FBFBEF047F2B99E0BF6", :AccountNum => "8228-5500", etc. }   # Doesn't have to be called CAppLogin as in the file, may be fixed

什么可能是最短的,最内置的Ruby方式来自动化哈希读取,我可以更新SessionID值并将其轻松存储回文件以供以后的程序运行?

我玩过YAML,REXML,但还是不打印我的(坏)示例试验。

2 个答案:

答案 0 :(得分:19)

您可以在Ruby中使用一些库来执行此操作。

Ruby工具箱可以很好地覆盖其中一些:

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

我使用XMLSimple,只需要gem然后使用xml_in加载到xml文件中:

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

如果您处于Rails环境中,则可以使用Active Support:

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

答案 1 :(得分:7)

使用Nokogiri解析带有名称空间的XML:

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"}

如果您知道 CAppLogin是根元素,您可以简化一下:

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"}