查找并用Nokogiri替换整个HTML节点 [英] Find and replace entire HTML nodes with Nokogiri
本文介绍了查找并用Nokogiri替换整个HTML节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个HTML,应该对其进行转换,将某些标签替换为另一个标签.
i have an HTML, that should be transformed, having some tags replaced with another tags.
我不知道这些标签,因为它们将来自数据库.因此,Nokogiri的set_attribute
或name
方法不适合我.
I don't know about these tags, because they will come from db. So, set_attribute
or name
methods of Nokogiri are not suitable for me.
在某种程度上,我需要这样做,就像下面的伪代码一样:
I need to do it, in a way, like in this pseudo-code:
def preprocess_content
doc = Nokogiri::HTML( self.content )
doc.css("div.to-replace").each do |div|
# "get_html_text" will obtain HTML from db. It can be anything, even another tags, tag groups etc.
div.replace self.get_html_text
end
self.content = doc.css("body").first.inner_html
end
我找到了Nokogiri::XML::Node::replace
方法.我认为这是正确的方向.
I found Nokogiri::XML::Node::replace
method. I think, it is the right direction.
此方法需要一些node_or_tags
参数.
我应该使用哪种方法从文本创建一个新的Node并将其替换为当前的Node?
Which method should i use to create a new Node from text and replace the current one with it?
推荐答案
喜欢:
doc.css("div.to-replace").each do |div|
new_node = doc.create_element "span"
new_node.inner_html = self.get_html_text
div.replace new_node
end
这篇关于查找并用Nokogiri替换整个HTML节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文