代码之家  ›  专栏  ›  技术社区  ›  Dave

如何在Nokogiri文档中检索唯一的父节点集?

  •  0
  • Dave  · 技术社区  · 7 年前

    leaf_nodes = doc.xpath("//*[not(child::*)]")
    

    我想检索这些子元素的父节点,所以现在,我正在做

        leaf_nodes.each_with_index do |leaf_node, index|
          node = leaf_node.parent
    ... process stuff
    

    但这有点低效,因为我要多次重新处理一些父节点。在我遍历所有内容之前,是否有方法检索唯一的父节点集?

    1 回复  |  直到 7 年前
        1
  •  0
  •   kiddorails    7 年前

    怎么样:

    leaf_nodes.map(&:parent).uniq.each_with_index do |node, index|
      # Here node is already unique parent node
      # process stuff
    end
    

    leaf_nodes.map(&:parent).uniq 将提取父对象,并在迭代之前为您提供唯一的父对象。这样你就不用打电话 在同一父元素上多次。