im using nokogiri.
i need to get the common xpath ancestor of group of elements.
im using nokogiri.
i need to get the common xpath ancestor of group of elements.
There we go
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>
added it to the NodeSet
class, so we can call it as a method.