【发布时间】:2012-08-16 17:33:06
【问题描述】:
有没有什么干净的方法可以用 Nokogiri 获取文本节点的内容?我现在正在使用
some_node.at_xpath( "//whatever" ).first.content
这对于获取文本来说似乎真的很冗长。
【问题讨论】:
有没有什么干净的方法可以用 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
【讨论】:
present? 和 blank? 方法。其中每一个都是等效的:doc.search('//text()').map(&:text).delete_if &:blank? 或 doc.search('//text()').map(&:text).keep_if &:present?
some_node.at('whatever').text。
只需寻找文本节点:
require 'nokogiri'
doc = Nokogiri::HTML(<<EOT)
<html>
<body>
<p>This is a text node </p>
<p> This is another text node</p>
</body>
</html>
EOT
doc.search('//text()').each do |t|
t.replace(t.content.strip)
end
puts doc.to_html
哪些输出:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<p>This is a text node</p>
<p>This is another text node</p>
</body></html>
顺便说一句,您的代码示例不起作用。 at_xpath( "//whatever" ).first 是多余的,会失败。 at_xpath 只会找到第一个匹配项,返回一个节点。 first 在这一点上是多余的,如果它可以工作的话,但它不会因为 Node 没有 first 方法。
我有
<data><foo>bar</foo></bar>,我如何在不执行doc.xpath_at( "//data/foo" ).children.first.content的情况下获得“栏”文本?
假设 doc 包含解析后的 DOM:
doc.to_xml # => "<?xml version=\"1.0\"?>\n<data>\n <foo>bar</foo>\n</data>\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"
【讨论】: