【问题标题】:converting from xml name-values into simple hash从 xml 名称值转换为简单的哈希
【发布时间】:2012-06-23 18:42:04
【问题描述】:

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

我的数据文件 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,但还不想打印我的(坏的)示例试验。

【问题讨论】:

  • 这叫做XML绑定(将XML映射到另一种语言的对象)或者XML转换!

标签: ruby xml yaml rexml


【解决方案1】:

您可以在 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')

【讨论】:

  • gem install xml-simple 谢谢,我会检查是否有简单的.xml_out 方法将其保存回文件...
  • 是的,xml_out 将采用数据结构(在您的情况下为哈希),并以 XML 编码返回它。
【解决方案2】:

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

【讨论】:

  • 谢谢,我更喜欢你的第二个例子,因为我不知道/不想关心根元素的名称是什么,它包含我需要的实际键/值对以某种方式编辑并保存回文件中。
猜你喜欢
  • 2014-05-10
  • 2023-03-26
  • 2021-07-13
  • 2011-02-08
  • 1970-01-01
  • 2019-09-21
  • 2015-05-12
  • 2016-08-26
  • 1970-01-01
相关资源
最近更新 更多