1require 'rexml/parsers/streamparser' 2require 'rexml/parsers/baseparser' 3require 'rexml/light/node' 4 5module REXML 6 module Parsers 7 class LightParser 8 def initialize stream 9 @stream = stream 10 @parser = REXML::Parsers::BaseParser.new( stream ) 11 end 12 13 def add_listener( listener ) 14 @parser.add_listener( listener ) 15 end 16 17 def rewind 18 @stream.rewind 19 @parser.stream = @stream 20 end 21 22 def parse 23 root = context = [ :document ] 24 while true 25 event = @parser.pull 26 case event[0] 27 when :end_document 28 break 29 when :start_element, :start_doctype 30 new_node = event 31 context << new_node 32 new_node[1,0] = [context] 33 context = new_node 34 when :end_element, :end_doctype 35 context = context[1] 36 else 37 new_node = event 38 context << new_node 39 new_node[1,0] = [context] 40 end 41 end 42 root 43 end 44 end 45 46 # An element is an array. The array contains: 47 # 0 The parent element 48 # 1 The tag name 49 # 2 A hash of attributes 50 # 3..-1 The child elements 51 # An element is an array of size > 3 52 # Text is a String 53 # PIs are [ :processing_instruction, target, data ] 54 # Comments are [ :comment, data ] 55 # DocTypes are DocType structs 56 # The root is an array with XMLDecls, Text, DocType, Array, Text 57 end 58end 59