答案 0 :(得分:3)
我们去了
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>
将其添加到NodeSet
类,因此我们可以将其称为方法。