Class: XTJ::Handlers::XMLHandler
- Inherits:
-
Object
- Object
- XTJ::Handlers::XMLHandler
- Includes:
- REXML::SAX2Listener, Tags
- Defined in:
- lib/xtj/handlers/xml_handler.rb
Instance Attribute Summary collapse
-
#xml_hash ⇒ Object
readonly
Returns the value of attribute xml_hash.
Instance Method Summary collapse
- #characters(text) ⇒ Object
- #end_element(_uri, _localname, _qname) ⇒ Object
-
#initialize ⇒ XMLHandler
constructor
A new instance of XMLHandler.
- #start_element(_uri, _localname, qname, attributes) ⇒ Object
Constructor Details
#initialize ⇒ XMLHandler
Returns a new instance of XMLHandler.
13 14 15 16 |
# File 'lib/xtj/handlers/xml_handler.rb', line 13 def initialize @xml_hash = {} @stack = [] end |
Instance Attribute Details
#xml_hash ⇒ Object (readonly)
Returns the value of attribute xml_hash.
11 12 13 |
# File 'lib/xtj/handlers/xml_handler.rb', line 11 def xml_hash @xml_hash end |
Instance Method Details
#characters(text) ⇒ Object
37 38 39 40 41 42 43 44 |
# File 'lib/xtj/handlers/xml_handler.rb', line 37 def characters(text) return if text.strip.empty? raise REXML::ParseException, 'Invalid XML' if @stack.empty? element = @stack.shift element.attributes[:@text] = text @stack.prepend(element) end |
#end_element(_uri, _localname, _qname) ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/xtj/handlers/xml_handler.rb', line 25 def end_element(_uri, _localname, _qname) if @stack.length > 1 child = @stack.shift parent = @stack.shift parent.add_to_attributes(child.tag, child.attributes) @stack.prepend(parent) else element = @stack.shift @xml_hash[element.tag] = element.attributes end end |
#start_element(_uri, _localname, qname, attributes) ⇒ Object
18 19 20 21 22 23 |
# File 'lib/xtj/handlers/xml_handler.rb', line 18 def start_element(_uri, _localname, qname, attributes) prefixed_attributes = attributes .transform_keys { |key| "_#{key}".to_sym } element = XMLTag.new(tag: qname.to_sym, attributes: prefixed_attributes) @stack.prepend(element) end |