Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 获取公共xpath祖先节点?_Ruby_Xpath_Nokogiri - Fatal编程技术网

Ruby 获取公共xpath祖先节点?

Ruby 获取公共xpath祖先节点?,ruby,xpath,nokogiri,Ruby,Xpath,Nokogiri,可能重复: 我用的是nokogiri 我需要获得元素组的公共xpath祖先。我们开始了 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 ancestor

可能重复:

我用的是nokogiri

我需要获得元素组的公共xpath祖先。

我们开始了

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>
需要“rubygems”
需要“nokogiri”
类Nokogiri::XML::NodeSet
共同祖先
如果为空,返回nil?
祖先=self.collect{e|e.祖先.to_a.reverse}
普通=零
祖先.shift.zip(*祖先)do |节点|
如果nodes.uniq.size>1,则中断
common=nodes.first
结束
返回公共
结束
结束
doc=Nokogiri::XML(DATA.read)
p doc.css('.leaf').common_.path
__结束__

将其添加到
节点集
类中,因此我们可以将其作为方法调用。

我们开始了

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>
需要“rubygems”
需要“nokogiri”
类Nokogiri::XML::NodeSet
共同祖先
如果为空,返回nil?
祖先=self.collect{e|e.祖先.to_a.reverse}
普通=零
祖先.shift.zip(*祖先)do |节点|
如果nodes.uniq.size>1,则中断
common=nodes.first
结束
返回公共
结束
结束
doc=Nokogiri::XML(DATA.read)
p doc.css('.leaf').common_.path
__结束__

将其添加到
节点集
类中,因此我们可以将其作为方法调用