Skip to content

Instantly share code, notes, and snippets.

@xianhuazhou
Created April 14, 2010 15:37
Show Gist options
  • Save xianhuazhou/365971 to your computer and use it in GitHub Desktop.
Save xianhuazhou/365971 to your computer and use it in GitHub Desktop.
#
# convert xml data to hash with hpricot
#
# by xianhua.zhou@gmail.com
require 'rubygems'
require 'hpricot'
require 'ap'
class ConvertXml
def initialize(filename)
@filename = filename
end
def get_valid_nodes(nodes)
nodes.find_all{|it|it.is_a? Hpricot::Elem}
end
def convert(xml_nodes = nil, parent_node = nil)
if xml_nodes.nil?
xml_nodes = Hpricot(File.read(@filename)).search('/')
key = :root
else
key = parent_node.name
end
# results
nodes = {}
get_valid_nodes(xml_nodes).each do |node|
children = get_valid_nodes(node.children)
nodes[key] = [] if nodes[key].nil?
nodes[key] << \
if children.size > 0
convert(children, node)
else
node
end
end
nodes
end
end
cx = ConvertXml.new('users.xml')
ap cx.convert[:root]
<?xml version="1.0" encoding="utf-8" ?>
<people>
<person>
<hi>
<name>zhou</name>
<info>test</info>
<age>12</age>
</hi>
<hello>world</hello>
</person>
<person>
<hi>
<name>li</name>
<info>hello</info>
<age>10</age>
</hi>
</person>
</people>
<?xml version="1.0" encoding="utf-8" ?>
<people>
nothing
</people>
<people>
<user>Me</user>
</people>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment