从 xml 名称值转换为简单的哈希 [英] converting from xml name-values into simple hash

查看:7
本文介绍了从 xml 名称值转换为简单的哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I don't know what name this goes by and that's been complicating my search.

我的数据文件 OX.session.xml 是(旧的?)形式

My data file OX.session.xml is in the (old?) form

<?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 数据格式到底叫什么?

What is that XML data format called exactly?

无论如何,我只想在我的 Ruby 代码中得到一个哈希,如下所示:

Anyway, all I want is to end up with one hash in my Ruby code like so:

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

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

What might be shortest, most built-in Ruby way to automate that hash read, in a way I can update the SessionID value and store it easily back into the file for later program runs?

我玩过 YAML、REXML,但还不想打印我的(坏的)示例试验.

I've played around with YAML, REXML but would rather not yet print my (bad) example trials.

推荐答案

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

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

Ruby 工具箱对其中一些有很好的介绍:

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

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

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

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

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

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

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

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

这篇关于从 xml 名称值转换为简单的哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆