Class: XMLCodec::XMLStreamObjectParser

Inherits:
Object
  • Object
show all
Defined in:
lib/stream_object_parser.rb

Overview

This is a XML Stream parser that returns ruby objects for whole elements. To do this a class must be defined as descending from XMLElement and having set elname or elnames. To use it all you have to do is define a listener that responds to methods of the form el_<element name> and define the importers for the elements as subclasses of XMLElement.

The listener will be passed XMLSOParserElement objects. The two relevant methods for it’s use are XMLSOParserElement#get_object and XMLSOParserElement#consume.

Instance Method Summary collapse

Constructor Details

#initialize(base_element, listener = nil) ⇒ XMLStreamObjectParser

Create a new parser with a listener.



64
65
66
67
68
69
70
71
72
# File 'lib/stream_object_parser.rb', line 64

def initialize(base_element, listener=nil)
  @base_element = base_element
  @listener = listener
  @children = Hash.new([])
  @currel = 0
  @elements = [XMLSOParserElement.new(nil, nil, nil, nil, nil, 0)]
  @id = 0
  @top_element = nil
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(methId, *args) ⇒ Object

Ignore everything except tags and text for now



135
136
# File 'lib/stream_object_parser.rb', line 135

def method_missing(methId, *args) #:nodoc:
end

Instance Method Details

#parse(text) ⇒ Object

Parse the text with the stream parser calling the listener on any events that it listens to.



94
95
96
# File 'lib/stream_object_parser.rb', line 94

def parse(text)
  REXML::Document.parse_stream(text, self)
end

#tag_end(name) ⇒ Object

:nodoc:



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/stream_object_parser.rb', line 115

def tag_end(name) #:nodoc:
  obj = curr_element
  
  if @listener.respond_to?("el_"+name)
    @listener.send("el_"+name, obj)
  end
  
  if not obj.consumed
    if prev_element
      prev_element.add_child(obj.get_object)
    end
    
    @top_element = obj
  end
      
  @elements.pop
  @currel -= 1
end

#tag_start(name, attrs) ⇒ Object

:nodoc:



104
105
106
107
108
109
# File 'lib/stream_object_parser.rb', line 104

def tag_start(name, attrs) #:nodoc:
  @elements << XMLSOParserElement.new(name, attrs, get_elclass(name), 
                                      curr_element, next_id, 
                                      curr_element.depth+1)
  @currel += 1
end

#text(text) ⇒ Object

:nodoc:



111
112
113
# File 'lib/stream_object_parser.rb', line 111

def text(text) #:nodoc:
  curr_element.add_child(text)
end

#top_elementObject

Get the current top element of the parse. This is usually used to get the root at the end of the parse.



100
101
102
# File 'lib/stream_object_parser.rb', line 100

def top_element
  @top_element.get_object if @top_element
end