views:

48

answers:

2

Suppose I have this HTML:

html = <div>Four score and seven years ago</div>

What's the best way to insert (say) an anchor tag after the word "score"? Note: I want to do this in terms of DOM manipulation (with Hpricot, e.g.) not in terms of text manipulation (e.g., no regexes)

A: 

i am not that fluent in ruby. but normally you should have: Element div - and TextNode "Four score and seven years ago"

now if you want to insert something you will have to:

  • split the text from the text node into two (the original should change to "Four score") with text search/split functions
  • create a Element
  • create a new text-node with the rest of the text
  • append the a-element to the div element and then append the newly created text node
Niko
+1  A: 
require 'rubygems'
require 'nokogiri'

doc = Nokogiri::XML(DATA)
text = doc.xpath('//text()').first
text.content =~ /^(.*score)(.*)$/
text.content = $1
node = Nokogiri::XML::Node.new('a',doc)
text.add_next_sibling node
node.add_next_sibling Nokogiri::XML::Text.new($2,doc)

puts doc.to_xml

__END__
<div>Four score and seven years ago</div>
Adrian