I love Nokogiri for everything XML, HTML and Ruby. I think the library has been in each project of mine for three or four years.

Today’s example I read an HTML file from a service and add nodes the tag. This is a basic extension of the Nokogiri documentation, but should help a basic case not illustrated well in the docs.

# Fetch a remote asset and translate it to Nokogiri
@page = Nokogiri::HTML::Document.parse(remote_asset)
@link = @page.css("body")
@meta = @page.css("head").css("meta")
# Create a new node and add the attributes
@thumb = Nokogiri::XML::Node.new "link", @page
@thumb["href"] = "http://application-bucket.s3.amazonaws.com/fancy/css/jquery.thumbs.css"
@thumb["type"] = "text/css"
@thumb["rel"] = "stylesheet"
# Attach the new node to the page
# Assign a new instance and get it ready for departure
@page = @page.to_html.html_safe


Leave a Reply

Your email address will not be published. Required fields are marked *