引入nokogiri递归让所有的孩子(Nokogiri recursively get all ch

2019-07-28 20:44发布

问题

我正在对各种URL的一些统计数据。 我想与孩子最集中的号码找到最高级别的元素。 我想跟进的方法是找出所有顶级元素,然后确定属于它了页面上的所有元素的百分比。

目标

  • 递归获得给定元素的所有儿童。

输入:一个引入nokogiri元

输出:引入nokogiri元素的数组或儿童总数的计数

建立

  • 红宝石1.9.2
  • 引入nokogiri宝石

我最终什么事来了(这个工作,但不是一样漂亮下面我所选择的答案)

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

Answer 1:

的横动方法产生当前节点和所有儿童的块,递归。

# 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


Answer 2:

# 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


文章来源: Nokogiri recursively get all children