使用Nokogiri查找并替换整个HTML节点

时间:2010-08-10 14:02:45

标签: html ruby-on-rails replace nokogiri transformation

我有一个HTML,应该进行转换,将一些标签替换为另一个标签。

我不知道这些标签,因为它们来自db。因此,Nokogiri的set_attributename方法不适合我。

我需要在某种程度上这样做,就像在这个伪代码中一样:

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方法。我认为,这是正确的方向。

此方法需要一些node_or_tags参数。

我应该使用哪种方法从文本创建新节点并用它替换当前节点?

1 个答案:

答案 0 :(得分:23)

就像那样:

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