Skip to content

@sunkencity /xml_to_arr.rb
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
XMLToArr
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"}]
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.