如何使用 Nokogiri 去除 HTML 标签之间的间隙?
假设我有这种标记:
<li> Some text </li>
<li> <strong> Some text </strong> hello</li>
我需要确保在开始
期望的结果:
<li>Some text </li>
<li><strong>Some text </strong> hello</li>
Say I have this kind of markup:
<li> Some text </li>
<li> <strong> Some text </strong> hello</li>
I need to ensure that there is no whitespace gap after the opening <li>
tag and before any enclosed text content. What is the best way to accomplish this with Nokogiri?
Desired result:
<li>Some text </li>
<li><strong>Some text </strong> hello</li>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
删除整个文档中的所有前导/尾随空格:
但是,请注意,这会将
Hello World
变成
< p>你好世界
。您可能需要更准确地指定您想要什么。
编辑:这是一个更好的解决方案,可以从元素的第一个子元素的所有文本节点中删除前导空格,并从最后一个子元素的文本节点中删除所有尾随空格:
在操作中看到:
编辑#2:以下是如何将其从
前面的文本节点上删除:
Removing all leading/trailing whitespace in the whole doc:
However, note that this will turn
<p>Hello <b>World</b></p>
into<p>Hello<b>World</b></p>
. You likely need to more precisely specify what you want.Edit: Here's a better solution that removes leading space from all text nodes that are the first child of an element, and all trailing space from text nodes that are the last child:
Seen in action:
Edit #2: Here's how to strip it just off text nodes at the front of
<li>
:您将遍历每个 li 并删除前导空格,直到找到一些文本:
You would traverse each li removing leading whitespace until you find some text:
操作
Nokogiri::HTML.fragment
时,xpath("//text()")
似乎不起作用。这就是我的想法
注意:使用 Ruby 2.3 语法
When manipulating a
Nokogiri::HTML.fragment
, thexpath("//text()")
doesn't seem to work.So here's what I came up with
Note: uses Ruby 2.3 syntax