修改html节点内的文本 - nokogiri

时间:2022-08-09 19:12:38

Let's say i have the following HTML:

假设我有以下HTML:

<ul><li>Bullet 1.</li>
<li>Bullet 2.</li>
<li>Bullet 3.</li>
<li>Bullet 4.</li>
<li>Bullet 5.</li></ul>

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:

我想用它来做的是用HTML和自身替换任何句号,问号或感叹号以及尾随的星号,然后转换回HTML。结果将是:

<ul><li>Bullet 1.*</li>
<li>Bullet 2.*</li>
<li>Bullet 3.*</li>
<li>Bullet 4.*</li>
<li>Bullet 5.*</li></ul>

I've been messing around with this a bit in IRB, but can't quite figure it out. here's the code i have:

我在IRB中一直在搞乱这一点,但不能完全理解它。这是我的代码:

 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}*") }

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?

返回的数组被正确解析,但我不确定如何将其转换回HTML。有没有其他方法可以用来修改inner_text?

2 个解决方案

#1


7  

What about this code?

这段代码怎么样?

doc.traverse do |x|
  if x.text?
    x.content = x.content.gsub(/(?<=[.!?])(?!\*)/, "#{$1}*")
  end
end

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.

遍历方法与搜索(“*”)几乎完全相同。然后检查节点是否为Nokogiri :: XML :: Text,如果是,则根据需要更改内容。

#2


-1  

Thanks to the post here Nokogiri replace tag values, I was able to modify it a bit and figure it out.

感谢这里的帖子Nokogiri替换标签值,我能够稍微修改它并弄明白。

doc = Nokogiri::HTML::DocumentFragment.parse(html)
doc.search("*").each do |node|
  dummy = node.add_previous_sibling(Nokogiri::XML::Node.new("dummy", doc))
  dummy.add_previous_sibling(Nokogiri::XML::Text.new(node.to_s.gsub(/(?<=[.!?])(?!\*)/, "#{$1}*"), doc))
  node.remove
  dummy.remove
end

puts doc.to_html.gsub("&lt;", "<").gsub("&gt;", ">")

#1


7  

What about this code?

这段代码怎么样?

doc.traverse do |x|
  if x.text?
    x.content = x.content.gsub(/(?<=[.!?])(?!\*)/, "#{$1}*")
  end
end

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.

遍历方法与搜索(“*”)几乎完全相同。然后检查节点是否为Nokogiri :: XML :: Text,如果是,则根据需要更改内容。

#2


-1  

Thanks to the post here Nokogiri replace tag values, I was able to modify it a bit and figure it out.

感谢这里的帖子Nokogiri替换标签值,我能够稍微修改它并弄明白。

doc = Nokogiri::HTML::DocumentFragment.parse(html)
doc.search("*").each do |node|
  dummy = node.add_previous_sibling(Nokogiri::XML::Node.new("dummy", doc))
  dummy.add_previous_sibling(Nokogiri::XML::Text.new(node.to_s.gsub(/(?<=[.!?])(?!\*)/, "#{$1}*"), doc))
  node.remove
  dummy.remove
end

puts doc.to_html.gsub("&lt;", "<").gsub("&gt;", ">")