ruby-on-rails - nokogiri 从 xml 到数组的多个元素

标签 ruby-on-rails ruby xml xpath nokogiri

我有一个 XML 新闻提要,我想从中抓取故事,以及每个故事的一些元素。 the original xml在这里,这是每个故事的示例。

<news:NewsResult>
        <news:Title>Essex Police/Fire</news:Title>
        <news:Url>http://www.gloucestertimes.com/local/x2118804357/Essex-Police-Fire</news:Url>
        <news:Source>Gloucester Daily Times</news:Source>
        <news:Snippet>ESSEX — An attempt to serve a summons to a Piper Lane resident was thwarted at 2:25 p.m. Monday when police discovered that the person no longer lives at that address. Alarms were set off in error on Belcher Street at 3:12 p.m. Monday, on Main Street at ...</news:Snippet>

到目前为止我有这样的代码:

def xml2Var(xmlin)
  #Parse received XML with Nokogiri
  doc = Nokogiri::XML(xmlin)

  #Remove  namespaces  
  doc.remove_namespaces!

  #print dat ish?  
# p p doc

#extract values.
  title = doc.xpath("//Title")
  snippet = doc.xpath("//Snippet")
  url = doc.xpath("//Url")
  source = doc.xpath("//Source")

我想将这些值放入每个故事的数组中。然后,将每个故事添加到故事数组中,以便我可以在我的 Rails 应用程序中显示它。 我有点设法做到这一点,但无法显示每个故事和每个故事的属性。我认为我对 Xpath 的使用是错误的?

最佳答案

要将故事放入数组中,您可以执行以下操作:

doc.css("NewsResult").map{|nr| [nr.at('Title'),nr.at('Snippet'),nr.at('Url'),nr.at('Source')].map(&:text)}

关于ruby-on-rails - nokogiri 从 xml 到数组的多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9505651/

相关文章:

ruby-on-rails - Rails 页面缓存在一定时间后自动过期

ruby-on-rails - 如何在 Rails Controller 中使用闭包?

ruby - 第三个 elsif 语句生成 nil 和不需要的输出

ruby-on-rails - Rails : After putting devise routes in namespace, 模型名称以命名空间为前缀。如何删除它?

ruby-on-rails - 如何在 Rails 中为 Mechanize 设置自定义用户代理

ruby-on-rails - 设计、Omniauth 和 Facebook 集成 session 错误

ruby - ActiveRecord迁移:unique => true being ignored?

java - 如何在 UI 中显示字符限制以及为用户数字化了多少?安卓Java

c++ - Qt:无法解析某些 svg 项目样式

xml - 斯卡拉 XML API : Why allow NodeSeq as attribute values?