public
Last active

XMLToArr

  • Download Gist
xml_to_arr.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
require 'rubygems'
require 'nokogiri'
require 'pp'
 
class XMLToArr < Nokogiri::XML::SAX::Document
def XMLToArr.parse str, hsh
[].tap do |returning|
Nokogiri::XML::SAX::Parser.new(self.new(returning, hsh)).parse(str)
end
end
def initialize returning, hsh
@searched_element = hsh.keys.first.to_s
@child_elements = hsh[hsh.keys.first].map &:to_s
@result_arr = returning
end
def start_element name, attrs = []
@current_element = name
@item = @child_elements.inject({}) { |hsh,x| hsh[x] = ""; hsh } if name == @searched_element
end
def characters str
@item[@current_element] << str if @child_elements.include? @current_element
end
def end_element name
@current_element = nil
@result_arr << @item if name == @searched_element
end
end
 
# Lets try it out
# File: text.xml:
# <items>
# <foo>
# <bar>a bar</bar>
# <baz>a baz</baz>
# </foo>
# <foo>
# <bar>another bar</bar>
# <baz>another baz</baz>
# </foo>
# </items>
#
#
# pp XMLToArr.parse(IO.read("test.xml"), :foo => [:bar, :baz])
#
# result:
#
# [{"baz"=>"a baz", "bar"=>"a bar"},
# {"baz"=>"another baz", "bar"=>"another bar"}]
#

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.