Created
March 4, 2011 15:04
-
-
Save sunkencity/854726 to your computer and use it in GitHub Desktop.
XMLToArr
This file contains hidden or 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
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