Nokogiri递归地得到所有的孩子



问题

我正在针对各种 URL 运行一些统计信息。我想找到孩子数量最集中的顶级元素。我想遵循的方法是识别所有顶级元素,然后确定页面上所有元素中属于它的百分比。

目标

  • 递归获取给定元素的所有子元素。

输入:Nokogiri 元素

输出:Nokogiri 元素数组或子元素总数的计数

设置

  • 红宝石 1.9.2
  • 野木宝石

我最终想出了什么(这有效,但不如我在下面选择的答案漂亮)

getChildCount(elem)
    children = elem.children
    return 0 unless children and children.count > 0
    child_count = children.count
    children.each do |child|
        child_count += getChildCount(child)
    end
    child_count
end

历方法以递归方式将当前节点和所有子节点生成到一个块中。

# if you would like it to be returned as an array, rather than each node being yielded to a block, you can do this
result = []
doc.traverse {|node| result << node }
result
# or, 
require 'enumerator'
result = doc.enum_for(:traverse).map
# Non-recursive
class Nokogiri::XML::Node
  def descendant_elements
    xpath('.//*')
  end
end
# Recursive 1
class Nokogiri::XML::Node
  def descendant_elements
    element_children.map{ |kid|
      [kid, kid.descendant_elements]
    }.flatten
  end
end
# Recursive 2
class Nokogiri::XML::Node
  def descendant_elements
    kids = element_children.to_a
    kids.concat(kids.map(&:descendant_elements)).flatten
  end
end

最新更新