I'm trying to convert an XML document into a Ruby hash for the first time, and having no success. I have my XML document, doc.xml
, in a folder along with my script hashrunner.rb
.
我第一次尝试将XML文档转换为Ruby散列,但没有成功。我有我的XML文档,doc。xml,和我的脚本hashrunner.rb放在一个文件夹中。
In hashrunner.rb
:
在hashrunner.rb:
require 'active_support/core_ext/hash'
hash = Hash.from_xml("doc.xml")
puts hash
The first line of the XML document is <?xml version="1.0" encoding="US-ASCII"?>
, if that is helpful.
XML文档的第一行是 ,如果有用的话。
In my console, when I run ruby hashrunner.rb
, I get the error message:
在我的控制台中,当我运行ruby hashrunner时。rb,我收到错误信息:
/Users/me/.rvm/gems/ruby-1.9.3-p374/gems/activesupport-4.0.0/lib/active_support/xml_mini/rexml.rb:34:in `parse':The document "doc.xml" does not have a valid root (REXML::ParseException)
As someone relatively new to Ruby, I don't understand what this means, and some internet searching didn't turn up an explanation, either. To start, I'm not even sure if I'm calling the XML file correctly in the from_xml
method, so please let me know if that's the case. I'd be open to using different gems or a different approach if that would help.
作为Ruby的新手,我不明白这意味着什么,一些互联网搜索也没有给出解释。首先,我甚至不确定在from_xml方法中是否正确地调用了XML文件,因此请让我知道这种情况是否存在。如果可以的话,我愿意使用不同的宝石或者不同的方法。
1 个解决方案
#1
7
I'm pretty sure Hash::from_xml
has to take an XML string, not a filename string. Try:
我非常确定哈希::from_xml必须使用XML字符串,而不是文件名字符串。试一试:
hash = Hash.from_xml(File.read("doc.xml"))
#1
7
I'm pretty sure Hash::from_xml
has to take an XML string, not a filename string. Try:
我非常确定哈希::from_xml必须使用XML字符串,而不是文件名字符串。试一试:
hash = Hash.from_xml(File.read("doc.xml"))