本文介绍了Nokogiri替换标签值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将foo替换为bar?
How to replace "foo" to "bar" ?
从
<h1>foo1<p>foo2<a href="foo3.com">foo4</a>foo5</p>foo6</h1>
至
<h1>bar1<p>bar2<a href="foo3.com">bar4</a>bar5</p>bar6</h1>
我只想替换标签内容,没有标签属性。
I want only replace tag inner content, without tag attributes.
任何想法?
推荐答案
require 'rubygems'
require 'nokogiri'
doc = Nokogiri::HTML(DATA)
doc.xpath('//text()').each {|foo|
dummy = foo.add_previous_sibling(Nokogiri::XML::Node.new("dummy", doc))
dummy.add_previous_sibling(Nokogiri::XML::Text.new(foo.to_s.gsub(/foo/, "bar"), doc))
foo.remove
dummy.remove
}
puts doc
__END__
<h1>foo1<p>foo2<a href="foo3.com">foo4</a>foo5</p>foo6</h1>
我会想到 foo.inner_html.gsub!(/ foo / bar)
,或者可能 foo.inner_html = foo.inner_html.gsub(/ foo /,bar)
t。
虚拟节点是保持新文本节点与旧文本节点成为一个。
I would have thought foo.inner_html.gsub!(/foo/, "bar")
works or maybe foo.inner_html = foo.inner_html.gsub(/foo/, "bar")
, but it doesn't.
The dummy node is to keep the new text node becoming one with the old text node.
这篇关于Nokogiri替换标签值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!