Created
December 22, 2010 20:48
-
-
Save rubiii/752080 to your computer and use it in GitHub Desktop.
Crack with a Nokogiri SAX parser
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
require "crack" | |
require "nokogiri" | |
module NokogiriParser | |
class Document < Nokogiri::XML::SAX::Document | |
def stack | |
@stack ||= [] | |
end | |
def start_element(name, attrs = []) | |
stack.push Crack::XMLUtilityNode.new(name, Hash[*attrs.flatten]) | |
end | |
def end_element(name) | |
if stack.size > 1 | |
last = stack.pop | |
stack.last.add_node last | |
end | |
end | |
def characters(string) | |
stack.last.add_node(string) unless string.strip.length == 0 || stack.empty? | |
end | |
alias cdata_block characters | |
end | |
end | |
document = NokogiriParser::Document.new | |
parser = Nokogiri::XML::SAX::Parser.new document | |
xml = File.read "some.xml" | |
Crack::XML.parser = parser | |
Crack::XML.parse xml | |
result = document.stack.length > 0 ? document.stack.pop.to_hash : {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment