Class: Saxy::Parser

Inherits:
Nokogiri::XML::SAX::Document
  • Object
show all
Includes:
Enumerable
Defined in:
lib/saxy/parser.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(xml_file, object_tag) ⇒ Parser

Returns a new instance of Parser.



19
20
21
22
# File 'lib/saxy/parser.rb', line 19

def initialize(xml_file, object_tag)
  @xml_file, @object_tag = xml_file, object_tag
  @tags, @elements = [], []
end

Instance Attribute Details

#callbackObject (readonly)

Will yield objects inside the callback after they’re built



17
18
19
# File 'lib/saxy/parser.rb', line 17

def callback
  @callback
end

#elementsObject (readonly)

Stack of elements built while traversing XML tree

First element is pushed to the stack only after finding the object_tag in the XML tree.



14
15
16
# File 'lib/saxy/parser.rb', line 14

def elements
  @elements
end

#tagsObject (readonly)

Stack of XML tags built while traversing XML tree



8
9
10
# File 'lib/saxy/parser.rb', line 8

def tags
  @tags
end

Instance Method Details

#cdata_block(cdata) ⇒ Object



49
50
51
# File 'lib/saxy/parser.rb', line 49

def cdata_block(cdata)
  current_element.append_value(cdata) if current_element
end

#characters(chars) ⇒ Object



53
54
55
# File 'lib/saxy/parser.rb', line 53

def characters(chars)
  current_element.append_value(chars) if current_element
end

#current_elementObject



61
62
63
# File 'lib/saxy/parser.rb', line 61

def current_element
  elements.last
end

#each(&blk) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/saxy/parser.rb', line 65

def each(&blk)
  if blk
    @callback = blk

    parser = Nokogiri::XML::SAX::Parser.new(self)

    if @xml_file.is_a?(IO)
      parser.parse_io(@xml_file)
    else
      parser.parse_file(@xml_file)
    end
  else
    to_enum
  end
end

#end_element(tag) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/saxy/parser.rb', line 36

def end_element(tag)
  tags.pop
  if element = elements.pop
    object = element.as_object

    if current_element
      current_element.set_attribute(tag, object)
    elsif callback
      callback.call(object)
    end
  end
end

#error(message) ⇒ Object

Raises:



57
58
59
# File 'lib/saxy/parser.rb', line 57

def error(message)
  raise ParsingError.new(message)
end

#start_element(tag, attributes = []) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/saxy/parser.rb', line 24

def start_element(tag, attributes=[])
  @tags << tag

  if tag == @object_tag || elements.any?
    elements << Element.new

    attributes.each do |(attr, value)|
      current_element.set_attribute(attr, value)
    end
  end
end