2009-09-28 4 views

Répondre

3

Nous y voilà

require 'rubygems' 
require 'nokogiri' 

class Nokogiri::XML::NodeSet 
    def common_ancestor 
    return nil if empty? 
    ancestors = self.collect{ |e| e.ancestors.to_a.reverse } 
    common = nil 
    ancestors.shift.zip(*ancestors) do |nodes| 
     break if nodes.uniq.size > 1 
     common = nodes.first 
    end 
    return common 
    end 
end 

doc = Nokogiri::XML(DATA.read) 
p doc.css('.leaf').common_ancestor.path 


__END__ 
<html><body><span> 
<div><p><h1><i><font class="leaf"/></i></h1></p></div> 
<div><div><div><div><table><tr><p><h1 class="leaf"/></p></tr></table></div></div></div></div> 
<p><h1><b class="leaf"/></h1></p> 
</span></body></html> 

ajouté à la classe NodeSet, donc on peut l'appeler comme méthode.