gpt4 book ai didi

ruby - 你如何计算Nokogiri节点后代的 "levels"个数?

转载 作者:数据小太阳 更新时间:2023-10-29 07:37:01 28 4
gpt4 key购买 nike

您可以调用Nokogiri::XML::Node#ancestors.size 来查看节点的嵌套深度。但是有没有办法确定嵌套最深的子节点的嵌套深度呢?

或者,您如何找到从一个节点下降的所有叶节点?

最佳答案

下面的代码猴子补丁 Nokogiri::XML::Node 是为了好玩,但当然你可以将它们提取为单独的方法,如果你喜欢的话。 (只有 height 方法是您问题的一部分,但我认为 deepest_leaves 方法可能很有趣。)

require 'nokogiri'
class Nokogiri::XML::Node
def depth
ancestors.size
# The following is ~10x slower: xpath('count(ancestor::node())').to_i
end
def leaves
xpath('.//*[not(*)]').to_a
end
def height
tallest = leaves.map{ |leaf| leaf.depth }.max
tallest ? tallest - depth : 0
end
def deepest_leaves
by_height = leaves.group_by{ |leaf| leaf.depth }
by_height[ by_height.keys.max ]
end
end

doc = Nokogiri::XML "<root>
<a1>
<b1></b1>
<b2><c1><d1 /><d2><e1 /><e2 /></d2></c1><c2><d3><e3/></d3></c2></b2>
</a1>
<a2><b><c><d><e><f /></e></d></c></b></a2>
</root>"

a1 = doc.at_xpath('//a1')
p a1.height #=> 4
p a1.deepest_leaves.map(&:name) #=> ["e1", "e2", "e3"]
p a1.leaves.map(&:name) #=> ["b1", "d1", "e1", "e2", "e3"]

编辑:只是回答问题时要简洁,不要将其包装在可重复使用的部分中:

p a1.xpath('.//*[not(*)]').map{ |n| n.ancestors.size }.max - a1.ancestors.size

关于ruby - 你如何计算Nokogiri节点后代的 "levels"个数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5694759/

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