2014-04-12 40 views
0

我正在完成内容迁移,我需要解析大量HTML以匹配新结构。用Nokogiri在img标签周围添加图形包装

我有很多带内联样式的图像,我需要删除在每个标签周围添加包装的样式。

这是我的方法:

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>在我的形象标签。我尝试用“包装”方法,但没有工作。

回答

0

我觉得wrap只适用于NodeSets。尝试通过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 
+0

它的工作原理,谢谢! –