从第三方Web服务解析Xml响应

时间:2012-02-08 10:57:15

标签: xml post https ruby-on-rails-2 curb

我已经为我的rails 2应用程序安装了cURB库,并且我能够将多个xml文件作为发布请求发送到Web服务的单个URL。除此之外,我在xml文件中收到来自Web服务的收据,我需要由我的应用程序解析并输出从提交的文件中创建的错误。 请一些人指导我使用一个好的库和教程来捕获响应和解析xml文档。

所有建议都表示赞赏。

1 个答案:

答案 0 :(得分:0)

除非您已经这样做,否则我建议您使用libxml2库来处理XML。 libxml2库作为每个主要Linux发行版的软件包提供。

gem install libxml-ruby

以下是一个独立的示例,它与Rails 2.3.14一起使用,展示了如何使用XML解析器解析curb对象的结果。然后演示如何使用XPath查询从解析的XML文档中选择元素。

require 'xml/libxml'
require 'curb'

# I have included this part so that this serves as a standalone example

ce = Curl::Easy.new("http://www.myexperiment.org/announcements.xml")
ce.perform

# This is the part that deals with parsing the XML result

doc = LibXML::XML::Parser.string(ce.body_str).parse

# You can then use XPath queries to process the results, e.g.:

doc.find("/announcements/announcement").each do |el|
  puts el.content
end

libxml-ruby的完整文档可用。