你举的例子并没有真正给出一个明确定义什么应该返回定义。文本节点是否被忽略?如果一个元素有多个<div>
子元素会发生什么?如果外部<div>
元素具有名为children
的属性,会发生什么情况?
除此之外,如果您有办法使用您选择的XML/HTML解析库的内置数据结构并使用XPath查询来到达,那么您可能不应构建这样的结构你想要的数据节点。
无视以上所有内容,这里是一个简单的开始,可能接近您的想法。
require "nokogiri"
class Nokogiri::XML::Node
def to_hash
# Build hash of attributes. Attribute values are split into arrays.
contents = Hash[attributes.collect { |name, value|
[name.to_sym, value.to_s.split(/\s+/)] }]
# Add array of child hashes recursively.
if element_children.any?
contents[:children] = element_children.collect { |child| child.to_hash }
end
# Return new hash with the element name as single key.
{ name.to_sym => contents }
end
end
使用方法如下:
doc = Nokogiri::XML('<div class="class-1 class-2" id="my-id">
<div class="classy">
</div>
</div>')
doc.root.to_hash
#=> { :div =>
# { :class => ["class-1", "class-2"],
# :children =>
# [ { :div =>
# { :class => ["classy"] }
# } ],
# :id => ["my-id"]
# }
# }
感谢您指出我到正确的方向:这里的结果:http://github.com/kuroir/Nokogiri-to-Hash – MarioRicalde 2010-08-19 01:24:19