2012-06-21 44 views
7

我不知道這個名稱是什麼,這使我的搜索變得複雜。從xml名稱值轉換爲簡單的散列表

我的數據文件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,但還不打印我的(壞)示例試用版。

+0

這是稱爲XML綁定(將XML映射到另一種語言的對象)或XML轉換! – Maarten

回答

16

有幾個您可以在Ruby中使用這些庫。

紅寶石工具箱中有幾個他們的一些好的報道:

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

我用XMLSimple,只需要創業板,然後使用xml_in在XML文件中加載:

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

如果您處於Rails環境中,您可以使用Active Support:

require ‘active_support’ 
session = Hash.from_xml('session.xml') 
+0

'gem install xml-simple'謝謝,我會檢查是否有簡單的'.xml_out'方法將它保存到文件中。 – Marcos

+0

是的,xml_out將採用數據結構(Hash,在你的情況下),並以XML編碼返回。 – ply

+0

Hash.from_xml採用xml字符串,而不是文件名... – NobodysNightmare

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

謝謝,我喜歡你的第二個例子,因爲我不知道/不想關心根元素的名稱,它包含我需要編輯並保存迴文件的實際鍵/值對不知何故。 – Marcos

相關問題