html - 使用 Nokogiri 查找和替换整个 HTML 节点

标签 html ruby-on-rails replace nokogiri transformation

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

我不知道这些标签,因为它们将来自数据库。所以,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 参数。

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

最佳答案

像那样:

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

关于html - 使用 Nokogiri 查找和替换整个 HTML 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3449767/

相关文章:

ruby-on-rails - 取消 ActiveRecord 中的依赖对象

matlab - 在 MATLAB 中以 0 到 1 和 1 到 0 的不同概率替换向量的元素

javascript - split 函数不适用于提供的正则表达式

java - 如何在Java中用不同的值替换字符串中多次出现的相同正则表达式模式

html - margin 溢出问题

php - 添加按价格排序和按名称排序

html - 如何在没有内容的情况下将 div 放到底部,同时仍然具有响应式设计?

javascript - Index.js.erb 文件在 Rails 5.1 中不起作用

ruby-on-rails - ActionController::RoutingError(没有路由匹配 [GET] "/assets/underscore-min.map")

javascript - 即使我有链接,如何强制打开我的 jQuery 对话框?