wma*_*but 11 ruby xhtml search nokogiri
我正在针对各种URL运行一些统计信息.我想找到最集中的孩子数量的顶级元素.我想要遵循的方法是识别所有顶级元素,然后确定页面上所有元素的百分比属于它.
输入:Nokogiri元素
输出:一系列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
Run Code Online (Sandbox Code Playgroud)
Joh*_*hat 30
的横动方法产生当前节点和所有儿童的块,递归.
# 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
Run Code Online (Sandbox Code Playgroud)
# 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
Run Code Online (Sandbox Code Playgroud)