【问题标题】:How to get the content of an XML node using XPath and Nokogiri如何使用 XPath 和 Nokogiri 获取 XML 节点的内容
【发布时间】:2011-07-19 14:15:45
【问题描述】:

我有这样的代码:

@doc = Nokogiri::HTML(open(url)
@doc.xpath(query).each do |html|

  puts html # how get content of a node
end

如何获取节点的内容而不是这样的:

<li class="stat">

【问题讨论】:

    标签: ruby nokogiri nodes


    【解决方案1】:

    这是 Nokogiri 的 README file 中的概要示例,展示了使用 CSS、XPath 或混合实现它的一种方法:

    require 'nokogiri'
    require 'open-uri'
    
    # Get a Nokogiri::HTML:Document for the page we’re interested in...
    
    doc = Nokogiri::HTML(open('http://www.google.com/search?q=tenderlove'))
    
    # Do funky things with it using Nokogiri::XML::Node methods...
    
    ####
    # Search for nodes by css
    doc.css('h3.r a.l').each do |link|
      puts link.content
    end
    
    ####
    # Search for nodes by xpath
    doc.xpath('//h3/a[@class="l"]').each do |link|
      puts link.content
    end
    
    ####
    # Or mix and match.
    doc.search('h3.r a.l', '//h3/a[@class="l"]').each do |link|
      puts link.content
    end
    

    【讨论】:

      【解决方案2】:

      请参阅 html.contenthtml.text

      请参阅Node documentation 了解更多信息。

      【讨论】:

      • 链接失效了,也许你现在想指向:rubydoc.info/gems/nokogiri/Nokogiri/XML/Node
      • 我修复了断开的链接。链接到非现场文档时,包含对您所做的最重要观点的摘要以及对文档的引用和归属非常重要。链接腐烂然后断开,当它们发生时,它们对任何人都没用。
      猜你喜欢
      • 2014-01-14
      • 1970-01-01
      • 1970-01-01
      • 2011-05-06
      • 2015-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多