gpt4 book ai didi

xpath - 从一组xpath中找到共同祖先?

转载 作者:行者123 更新时间:2023-12-03 17:20:17 25 4
gpt4 key购买 nike

说我有

html/body/span/div/p/h1/i/font
html/body/span/div/div/div/div/table/tr/p/h1
html/body/span/p/h1/b
html/body/span/div


我如何获得共同祖先?在这种情况下,span将是“ font,h1,b,div”的共同祖先将是“ span”

最佳答案

要查找两个节点之间的共同血统:

(node1.ancestors & node2.ancestors).first


与多个节点一起使用的更通用的功能:

# accepts node objects or selector strings
class Nokogiri::XML::Element
def common_ancestor(*nodes)
nodes = nodes.map do |node|
String === node ? self.document.at(node) : node
end

nodes.inject(self.ancestors) do |common, node|
common & node.ancestors
end.first
end
end

# usage:

node1.common_ancestor(node2, '//foo/bar')
# => <ancestor node>

关于xpath - 从一组xpath中找到共同祖先?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1485211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com