2013-08-31 234 views
1

Nokogiri::XML::DocumentFragment中删除所有标签的简单方法是什么?只保留空格分隔的文本?如何将HTML标记转换为纯文本?

我想改造:

Hello<br>My name is McOmghall 

到:

Hello My name is McOmghall 

我的解决办法是:

Nokogiri::XML.fragment(html_text).children.to_a.flatten.select { |node| node.class == Nokogiri::XML::Text} 

,然后串联数组将每个元素之间的空间,但我认为它不是最理想的,也不是很清楚。


编辑:

这是我的最终解决方案:

Nokogiri::XML.fragment(html_text).xpath('.//text()').map(&:text).join(' ') 
+0

是否要替换原有文档或仅输出所提到的格式?这是一个混乱.. –

+0

只有输出,但我不介意修改原来的。 –

回答

5
root = Nokogiri::HTML('<div id="test">Hello<br>My name is McOmghall</div>') 
root.at_css('#test').text 
# => "HelloMy name is McOmghall" 
root.at_css('#test').xpath('.//text()').map(&:text) 
# => ["Hello", "My name is McOmghall"] 
p root.at_css('#test').xpath('.//text()').map(&:text).join(' ') 
# => "Hello My name is McOmghall" 
0

如果之前或br后有没有空间,也不会有在文本

空间
doc = Nokogiri::HTML 'Hello<br>My name is McOmghall' 
doc.text 
#=> "HelloMy name is McOmghall" 

它'很容易每br虽然后添加一个空格:

doc.search('br').each{|br| br.after ' '} 
doc.text 
#=> "Hello My name is McOmghall" 
2

Nokogiri有一个非常方便的方法text?这种情况:

html = "Hello<br>My name is McOmghall"  

Nokogiri::HTML.fragment(html).children.select(&:text?).join(' ') 
# => "Hello My name is McOmghall"