Hpricot looping with index?
I have the following HTML doc :
<ul>
<li><span>Some text</span></li>
<li><span>Some other text</span></li>
<li><span>Some more text</span></li>
</ul>
How can I use Hpricot to loop on the list items and insert some new HTML at the beginning of each, so that I get the following :
<ul>
<li><span>1</span><span>Some text</span></li>
<li><span>2</span><span>Some other text</span></li>
<li><span>3</span><span>Some more text</span></li>
</ul>
If the new span's content were fixed, I could use :
(doc/"li").prepend "<span>fixed&开发者_C百科lt;/span>"
My problem comes from the variable span's content : how can I use an index in the prepend loop?
Try this code:
require 'rubygems'
require 'hpricot'
html = <<-EOF
<ul>
<li><span>Some text</span></li>
<li><span>Some other text</span></li>
<li><span>Some more text</span></li>
</ul>
EOF
doc = Hpricot(html)
(doc/'li/span').each_with_index do |element,index|
value = index + 1
element.before "<span>#{value}</span>"
end
puts doc.to_s
Use each_child to iterate over each of the li elements, and use a block to increment the index for each iteration.
精彩评论