你如何利用Nokogiri消除HTML标签之间的差距?

dan*_*dan 2 ruby nokogiri

说我有这种标记:

<li>    Some text </li>
<li> <strong>  Some text </strong> hello</li>
Run Code Online (Sandbox Code Playgroud)

我需要确保在开始<li>标记之后和任何封闭的文本内容之前没有空格.使用Nokogiri实现这一目标的最佳方法是什么?

期望的结果:

<li>Some text </li>
<li><strong>Some text </strong> hello</li>
Run Code Online (Sandbox Code Playgroud)

Phr*_*ogz 6

删除整个文档中的所有前导/尾随空格:

doc.xpath('//text()').each do |node|
  if node.content=~/\S/
    node.content = node.content.strip
  else
    node.remove
  end
end
Run Code Online (Sandbox Code Playgroud)

但请注意,这将<p>Hello <b>World</b></p>变为<p>Hello<b>World</b></p>.您可能需要更精确地指定您想要的内容.

编辑:这是一个更好的解决方案,它从作为元素的第一个子节点的所有文本节点中删除前导空格,并从作为最后一个子节点的文本节点中删除所有尾随空格:

doc.xpath('//text()[1]').each{ |t|      t.content = t.content.lstrip }
doc.xpath('//text()[last()]').each{ |t| t.content = t.content.rstrip }
Run Code Online (Sandbox Code Playgroud)

看到行动:

html = '<ul>
  <li>    First text </li>
  <li> <strong>  Some text </strong> </li>
  <li> I am <b>  embedded  </b> and need <i>some </i>  <em>spaces</em>. </li>
</ul>'

require 'nokogiri'
doc = Nokogiri.HTML(html)
doc.xpath('//text()[1]').each{ |t|      t.content = t.content.lstrip }
doc.xpath('//text()[last()]').each{ |t| t.content = t.content.rstrip }
puts doc.root
#=> <html><body><ul>
#=> <li>First text</li><li><strong>Some text</strong></li>
#=>   <li>I am <b>embedded</b> and need <i>some</i>  <em>spaces</em>.</li></ul></body></html>
Run Code Online (Sandbox Code Playgroud)

编辑#2:以下是如何从前面的文本节点剥离它<li>:

doc.xpath('//li/text()[1]').each{ |t| t.content = t.content.lstrip }
Run Code Online (Sandbox Code Playgroud)