使用Nokogiri在img标签周围添加一个图形包装器

时间:2014-04-12 09:05:52

标签: ruby nokogiri

我正在完成内容迁移,我需要解析大量HTML以匹配新结构。

我有很多内嵌样式的图片,我需要删除样式,在每个标记周围添加一个包装。

这是我的方法:

  def convert_imgtag(html)
    html_body = Nokogiri::HTML::fragment(html)
    html_body.xpath('.//img').each do |img|

      ****

      img.xpath('.//@style').remove
    end
    html_body.to_html
  end

我添加 * 的地方*我需要在我的图片标记周围添加<figure class="center-image"> </figure>。我尝试使用“换行”方法,但是不行。

1 个答案:

答案 0 :(得分:0)

我认为wrap只适用于NodeSet。尝试将这些更改拆分为img-nodes上的两次运行。

html_body = Nokogiri::HTML::fragment(html)

nodes = html_body.xpath('.//img')
nodes.wrap('<figure class="center-image"> </figure>')
nodes.each do |img|
  img.xpath('.//@style').remove
end