开发者

Find and replace entire HTML nodes with Nokogiri

开发者_高级运维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?


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜