Find and replace entire HTML nodes with Nokogiri

有些话、适合烂在心里 提交于 2019-11-29 17:34:14

问题


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

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

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

This method expects some node_or_tags parameter.

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


回答1:


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


来源:https://stackoverflow.com/questions/3449767/find-and-replace-entire-html-nodes-with-nokogiri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!