Class: LibXMLEnumparse::Parser::EnumCallbacks

Inherits:
Object
  • Object
show all
Includes:
LibXML::XML::SaxParser::Callbacks
Defined in:
lib/libxml_enumparse.rb

Instance Method Summary collapse

Constructor Details

#initialize(tag) ⇒ EnumCallbacks

Returns a new instance of EnumCallbacks.



13
14
15
16
17
# File 'lib/libxml_enumparse.rb', line 13

def initialize(tag)
  @tag = tag
  @buf = StringIO.new
  @layer = 0
end

Instance Method Details

#on_characters(chars) ⇒ Object



33
34
35
# File 'lib/libxml_enumparse.rb', line 33

def on_characters(chars)
  @buf << "#{CGI.escapeHTML(chars)}\n" if @layer.positive?
end

#on_end_element(element) ⇒ Object



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

def on_end_element(element)
  return if @buf.length.zero?

  @layer -= 1 if element == @tag
  @buf << "</#{element}>\n" if @layer.positive?
  if @layer.zero? && element == @tag
    @buf << "</#{element}>\n"
    Fiber.yield(@buf.string)
    @buf = StringIO.new
  end
end

#on_start_element(element, attributes) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/libxml_enumparse.rb', line 19

def on_start_element(element, attributes)
  @layer += 1 if element == @tag
  return if @layer.zero?

  if attributes.empty?
    @buf << "<#{element}>"
  else
    attr_pairs = attributes.map do |k, v|
      "#{k}=\"#{v.gsub('"', "%22").gsub("&", "%26")}\""
    end.join(" ")
    @buf << "<#{element} #{attr_pairs}>"
  end
end