Nokogiri文本节点内容

是否有任何干净的方法来获取Nokogiri的文本节点的内容? 现在我正在使用

some_node.at_xpath( "//whatever" ).first.content 

这对于获取文本来说似乎非常冗长。

想要文字吗?

 doc.search('//text()').map(&:text) 

也许你不想要所有的空白和噪音。 如果只想要包含单词字符的文本节点,

 doc.search('//text()').map(&:text).delete_if{|x| x !~ /\w/} 

编辑:您似乎只想要单个节点的文本内容:

 some_node.at_xpath( "//whatever" ).text 

只需查找文本节点:

 require 'nokogiri' doc = Nokogiri::HTML(<  

This is a text node

This is another text node

EOT doc.search('//text()').each do |t| t.replace(t.content.strip) end puts doc.to_html

哪个输出:

   

This is a text node

This is another text node

顺便说一下,你的代码示例不起作用。 at_xpath( "//whatever" ).first是多余的,会失败。 at_xpath只会找到第一个匹配项,返回一个Node。 first是多余的,如果它可以工作,但它不会因为Node没有first一种方法。


我有bar ,如何在不执行doc.xpath_at( "//data/foo" ).children.first.content情况下获取“bar”文本?

假设doc包含解析的DOM:

 doc.to_xml # => "\n\n bar\n\n" 

第一次出现:

 doc.at('foo').text # => "bar" doc.at('//foo').text # => "bar" doc.at('/data/foo').text # => "bar" 

获取所有事件并采取第一个:

 doc.search('foo').first.text # => "bar" doc.search('//foo').first.text # => "bar" doc.search('data foo').first.text # => "bar"