修改 html 节点内的文本 - nokogiri [英] Modifying text inside html nodes - nokogiri
问题描述
假设我有以下 HTML:
Let's say i have the following HTML:
<ul><li>Bullet 1.</li>
<li>Bullet 2.</li>
<li>Bullet 3.</li>
<li>Bullet 4.</li>
<li>Bullet 5.</li></ul>
我希望用它来做的是用它自己和一个尾随星号替换任何句号、问号或感叹号,这是在 HTML 节点内,然后转换回 HTML.所以结果是:
What I wish to do with it, is replace any periods, question marks or exclamation marks with itself and a trailing asterisk, that is inside an HTML node, then convert back to HTML. So the result would be:
<ul><li>Bullet 1.*</li>
<li>Bullet 2.*</li>
<li>Bullet 3.*</li>
<li>Bullet 4.*</li>
<li>Bullet 5.*</li></ul>
我一直在 IRB 中对此进行了一些处理,但无法完全弄清楚.这是我的代码:
I've been messing around with this a bit in IRB, but can't quite figure it out. here's the code i have:
html = "<ul><li>Bullet 1.</li>
<li>Bullet 2.</li>
<li>Bullet 3.</li>
<li>Bullet 4.</li>
<li>Bullet 5.</li></ul>"
doc = Nokogiri::HTML::DocumentFragment.parse(html)
doc.search("*").map { |n| n.inner_text.gsub(/(?<=[.!?])(?!\*)/, "#{$1}*") }
返回的数组已正确解析,但我不确定如何将其转换回 HTML.我可以使用另一种方法来修改inner_text吗?
The array that comes back is parsed out correctly, but I'm just not sure on how to convert it back into HTML. Is there another method i can use to modify the inner_text as such?
推荐答案
这段代码怎么样?
doc.traverse do |x|
if x.text?
x.content = x.content.gsub(/(?<=[.!?])(?!\*)/, "#{$1}*")
end
end
traverse
方法与 search("*").each
的作用几乎相同.然后检查该节点是否为 Nokogiri::XML::Text
,如果是,则根据需要更改 content
.
The traverse
method does pretty much the same as search("*").each
. Then you check that the node is a Nokogiri::XML::Text
and, if so, change the content
as you wished.
这篇关于修改 html 节点内的文本 - nokogiri的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!