【问题标题】:How do I parse the XML document using Nokogiri? [closed]如何使用 Nokogiri 解析 XML 文档? [关闭]
【发布时间】:2013-12-13 21:33:17
【问题描述】:

我正在尝试解析来自 Digital Trends 的 RSS 提要。我无法获得属性。比如我需要获取<enclosure>标签内图片的URL。

XML 文件是:

<item>   
  <title>   
    Xbox One returns to Best Buy with five new holiday bundles
  </title>
  <link>
    http://www.digitaltrends.com/gaming/xbox-one-returns-best-buy-five-new-holiday-    bundles/
  </link>
  <pubDate>Thu, 12 Dec 2013 23:59:20 +0000</pubDate>
  <enclosure url="http://icdn7.digitaltrends.com/image/microsoft-xbox-one-review-system-v2-100x100-c.jpg" length="0" type="image/png"/>
</item>

我该怎么做?

【问题讨论】:

  • 你试过什么?还是您希望我们为您编写它? Nokogiri's tutorials 对此进行了足够详细的介绍,以使这项工作变得轻松。 “要求代码的问题必须证明对正在解决的问题有最低限度的了解。包括尝试的解决方案、它们为什么不起作用以及预期的结果。另请参阅:Stack Overflow question checklist
  • 这是RSS。不要手动解析它。使用 RSS 解析器。
  • 这基本上是stackoverflow.com/questions/8584361/…的复制品
  • 根据我的经验,即使是 RSS 解析器也无法解析真实世界的 RSS,因为它是一个被滥用的规范。折腾 ATOM 和 RDF,它需要一个手动解析器。从罐头开始,看看它是否有效,但如果它因简单的提要之外的任何内容而失败,请不要感到惊讶。
  • @theTinMan require 'rubygems' require 'nokogiri' require 'open-uri' doc=Nokogiri::XML(open('http://www.digitaltrends.com/feed/')) doc.xpath('//item').each do |t| doc.xpath('//item').each do |t| p t.at_xpath('./title').content p t.at_xpath('./title').content p t.at_xpath('./description').content p t.at_xpath('./pubDate').content p t.at_css('enclosure')span @987654

标签: ruby xml-parsing nokogiri


【解决方案1】:
xml = Nokogiri::XML(...)
item = xml.xpath('//item')
item.at('enclosure')['url']

xml = Nokogiri::XML(...)
item = xml.xpath('//item')
item.at('enclosure').attr('url')

第一个例子返回一个字符串,第二个例子返回一个代表字符串值的Nokogiri::XML::Attr实例。

当然,替换

Nokogiri::XML(...)

根据您的 XML 文档的来源进行适当的文档解析。

您可能想阅读文章Searching an HTML / XML DocumentNokogiri::XML::Node API 文档中还提供了更多详细信息。

【讨论】:

  • 小心item.at('enclosure').firstat 返回单个 Node,而不是 NodeSet,并且 Node 没有 first 方法。 item.search('enclosure').first 不过可以。
  • 我的错,我最初使用css而不是改为at。我修复了代码,谢谢。
【解决方案2】:

尝试@doc.xpath("//enclosure")[0].attr("url"),假设您已将文档加载到@doc

【讨论】:

    【解决方案3】:

    试试这个代码:

    require 'nokogiri'
    
    doc = Nokogiri::HTML IO.read( 'file.xml' )
    e = doc.css( 'enclosure' )
    puts e.attr( 'url' )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多