我正试图用Mechanize获取一个远程xml文件,以获取icecast状态信息。但我在将XML文件从Mechanize::File
格式传递到字符串或XMLSimple可以使用的某种XML格式时遇到问题。
XML文档如下所示:
<icestats>
<admin>[email protected]</admin>
<!-- ... -->
</icestats>
我的代码现在看起来是这样的:
require 'mechanize'
require 'xmlsimple'
server = 'example.net'
port = 8000
user = 'stackoverflow'
password = 'hackme'
agent = Mechanize.new
agent.user_agent_alias = 'Linux Firefox'
agent.add_auth("http://#{server}:#{port}/admin/status.xml", user, password)
agent.get("http://#{server}:#{port}/admin/status.xml")
xml = agent.current_page
status = XmlSimple.xml_in(xml)
puts status['admin']
这应该输出:
[email protected]
但它抛出:
/home/user/.gem/ruby/1.9.1/gems/xml-simple-1.1.2/lib/xmlsimple.rb:191:in 'xml_in': Could not parse object of type: <Mechanize::File>. (ArgumentError)
现在,我知道xmlsimple需要一个字符串,因此我尝试将
Mechanize::File
格式转换为字符串,将最后一行替换为:status = XmlSimple.xml_in(xml.to_s)
但这引发了一个更奇怪的例外:
/usr/lib64/ruby/1.9.1/rexml/parsers/baseparser.rb:406:in `block in pull_event': Undefined prefix Mechanize: found (REXML::UndefinedNamespaceException)
from /usr/lib64/ruby/1.9.1/set.rb:222:in `block in each'
from /usr/lib64/ruby/1.9.1/set.rb:222:in `each_key'
from /usr/lib64/ruby/1.9.1/set.rb:222:in `each'
from /usr/lib64/ruby/1.9.1/rexml/parsers/baseparser.rb:404:in `pull_event'
from /usr/lib64/ruby/1.9.1/rexml/parsers/baseparser.rb:183:in `pull'
from /usr/lib64/ruby/1.9.1/rexml/parsers/treeparser.rb:22:in `parse'
from /usr/lib64/ruby/1.9.1/rexml/document.rb:231:in `build'
from /usr/lib64/ruby/1.9.1/rexml/document.rb:43:in `initialize'
from /home/user/.gem/ruby/1.9.1/gems/xml-simple-1.1.2/lib/xmlsimple.rb:965:in `new'
from /home/user/.gem/ruby/1.9.1/gems/xml-simple-1.1.2/lib/xmlsimple.rb:965:in `parse'
from /home/user/.gem/ruby/1.9.1/gems/xml-simple-1.1.2/lib/xmlsimple.rb:164:in `xml_in'
from /home/user/.gem/ruby/1.9.1/gems/xml-simple-1.1.2/lib/xmlsimple.rb:203:in `xml_in'
from debugging.rb:16:in `<main>'
我的方法怎么了?当我下载XML文件并使用本地XML文件时,上面的代码可以按需要工作。
我特别想寻找机械化的解决方案,而不是Nokogiri。
最佳答案
尝试更改:
xml = agent.current_page
到:
xml = agent.current_page.body
关于ruby - 如何在ruby中使用Mechanize和XMLSimple解析XML?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15113358/