我有一个HTML内容,如--
html = "<table id="soa_table" class="table table-striped table-bordered table-condensed soa-table"><thead><tr><th>SoA</th><th id="423" class="soa-column text-center">V1</th><th id="424" class="soa-column text-center">V2</th></tr></thead><tbody><tr><td class="soa-row" id="631">Label 1</td><td class="soa-element text-center" form_id="631" visit_id="423" id="484"><span class="glyphicon glyphicon-ok text-success"></span></td><td class="soa-element" form_id="631" visit_id="424" id="0"> </td></tr><tr><td class="soa-row" id="632">Label 2</td><td class="soa-element text-center" form_id="632" visit_id="423" id="485"><span class="glyphicon glyphicon-ok text-success"></span></td><td class="soa-element" form_id="632" visit_id="424" id="0"> </td></tr><tr><td class="soa-row" id="633">Label 3</td><td class="soa-element" form_id="633" visit_id="423" id="0"> </td><td class="soa-element text-center" form_id="633" visit_id="424" id="486"><span class="glyphicon glyphicon-ok text-success"></span></td></tr></tbody></table>"
现在我通过 Nokogiri 解析了它,并尝试将空格 gsub 为---
Nokogiri::HTML(html).at('table').to_html.gsub(/>s+</, "><")
但它不起作用
删除没有文本的标签之间不需要的空格
我的意思是这种空间:
<td class="soa-element" form_id="631" visit_id="424" id="0"> </td>
^
这是一个包含单个空格的文本节点。
让我们使用一个较小的示例:
html = '<foo>value</foo><bar> </bar>'
doc = Nokogiri::HTML.fragment(html)
您可以使用PP
来检查解析的文档结构:
require 'pp'
pp doc
输出:
#(DocumentFragment:0x3fe819894018 {
name = "#document-fragment",
children = [
#(Element:0x3fe819891b9c { name = "foo", children = [ #(Text "value")] }),
#(Element:0x3fe819891ae8 { name = "bar", children = [ #(Text " ")] })]
})
文档包含两个文本节点,一个带有"value"
另一个带有" "
。
为了删除后者,我们可以遍历文档并删除所有仅包含空格的文本节点:
doc.traverse { |node| node.remove if node.text? && node.text !~ /S/ }
pp doc
输出:
#(DocumentFragment:0x3fe819894018 {
name = "#document-fragment",
children = [
#(Element:0x3fe819891b9c { name = "foo", children = [ #(Text "value")] }),
#(Element:0x3fe819891ae8 { name = "bar" })]
})
最后,我们可以序列化文档:
doc.to_html
#=> "<foo>value</foo><bar></bar>"
删除仅空格的文本节点:
doc.search('//text()[normalize-space()=""]').remove
使用示例进行更新:
Nokogiri::HTML('<b></b> <b></b>').search('//text()[normalize-space()=""]').remove
#=> [#<Nokogiri::XML::Text:0x197ad78 " ">]
gsub
不会替换到源对象中。 gsub!
确实如此。 另外,你根本不需要Nokogiri。
require 'nokogiri'
puts 'Needlessly using Nokogiri'
html = "<p> </p>"
new_html = Nokogiri::HTML(html).at('p').to_html.gsub(/>s+</, '><')
puts html
puts new_html
puts '-' * 20
puts 'Solution #1'
html = "<p> </p>"
new_html = html.gsub(/>s+</, '><')
puts html
puts new_html
puts '-' * 20
puts 'Solution #2'
html = "<p> </p>"
puts html
html.gsub!(/>s+</,'><')
puts html
该程序的输出是:
Needlessly using Nokogiri <p> </p> <p></p> -------------------- Solution #1 <p> </p> <p></p> -------------------- Solution #2 <p> </p> <p></p>