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

时间:2021-12-01 19:13:04

i have an HTML, that should be transformed, having some tags replaced with another tags.

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

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.

我不知道这些标签,因为它们将来自db。所以,Nokogiri的set_attribute或name方法不适合我。

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

I found Nokogiri::XML::Node::replace method. I think, it is the right direction.

我找到了Nokogiri :: XML :: Node :: replace方法。我认为,这是正确的方向。

This method expects some node_or_tags parameter.

此方法需要一些node_or_tags参数。

Which method should i use to create a new Node from text and replace the current one with it?

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

1 个解决方案

#1


22  

Like that:

像那样:

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

#1


22  

Like that:

像那样:

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