Created
April 14, 2010 15:37
-
-
Save xianhuazhou/365971 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# 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] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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