使用Nokogiri将标签替换为?

如何使用nokogiri将所有img标签替换为图像标签? 这是为了利用Rails自动插入正确资产服务器的能力?

require 'nokogiri' class ToImageTag def self.convert Dir.glob("app/views/**/*").each do |filename| doc = Nokogiri::HTML(File.open(filename)) doc.xpath("//img").each |img_tags| # grab the src and all the attributes and move them to ERB end # rewrite the file end rescue => err puts "Exception: #{err}" end end 

有点受到maerics响应的启发,我创建了一个执行此操作的脚本。 它没有HTML实体的问题,因为它只使用nokogiri输出作为替换指南。 实际替换是使用String#gsub完成的!

https://gist.github.com/1254319

我能想出的最接近的如下:

 # ...... Dir.glob("app/views/**/*").each do |filename| # Convert each "img" tag into a text node. doc = Nokogiri::HTML(File.open(filename)) doc.xpath("//img").each do |img| image_tag = "<%= image_tag('#{img['src']}') %>" img.replace(doc.create_text_node(image_tag)) end # Replace the new text nodes with ERB markup. s = doc.to_s.gsub(/(<%|%>)/) {|x| x=='<%' ? '<%' : '%>'} File.open(filename, "w") {|f| f.write(s)} end 

此解决方案将对包含序列“ &lt% ”或“ %> ”的任何文件造成严重破坏(例如,如果您在HTML中描述ERB语法)。 问题是你正在尝试使用XML解析器用必须转义的文本替换XML节点,所以我不确定你能做得比这更好,除非有一些隐藏的“ raw_outer_xml=(str) “ 方法。

你最好的整体赌注是编写一个自定义SAX解析器,它只是回显给你的回调数据(或将它存储在一个字符串缓冲区中),除非它是带有“img”的“start_element”,在这种情况下它会写ERB序列。