tags:

views:

35

answers:

3

I am trying to write a Ruby script that would read a local HTML file, and insert some more HTML (basically a string) into it after a certain #divid.

I am kinda noob so please don't hesitate to put in some code here.

Thanks

A: 

so you want a plain HTML code???

anish
the Ruby code, someone suggested Nokogiri
M Wash
+1  A: 

I was able to this by following...

doc = Nokogiri::HTML(open('file.html'))
data = "<div>something</div>"
doc.children.css("#divid").first.add_next_sibling(data)

And then (over)write the file with same data...

File.open("file.html", 'w') {|f| f.write(doc.to_html) }
M Wash
A: 

This is a bit more correct way to do it:

html = '<html><body><div id="certaindivid">blah</div></body></html>'
doc = Nokogiri::HTML(html)
doc.at_css('div#certaindivid').add_next_sibling('<div>junk goes here</div>')

print doc.to_html 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"&gt;
<html><body>
<div id="certaindivid">blah</div>
<div>junk goes here</div>
</body></html>

Notice the use of .at_css(), which finds the first occurrence of the target node and returns it, avoiding getting a nodeset back, and relieving you of the need to grab the .first() node.

Greg