Class: XML::SAX::Builder

Inherits:
Filter
  • Object
show all
Defined in:
lib/xml-sax-machines/builder.rb

Overview

Build a Nokogiri::XML::Document from a SAX stream.

Example

builder =  XML::SAX::Builder.new
parser  =  Nokogiri::XML::SAX::PushParser.new(builder)
parser  << %q{<root>xml content</root>}
parser.finish

puts builder.document.children.to_s #=> xml content

See

  • XML::SAX::Filter

– TODO:

  • Namespaces.

Direct Known Subclasses

FragmentBuilder

Instance Attribute Summary collapse

Attributes inherited from Filter

#filter

Instance Method Summary collapse

Methods inherited from Filter

#end_document, #error, #warning

Instance Attribute Details

#documentObject (readonly)

The document object.

Returns

Nokogiri::XML::Document



27
28
29
# File 'lib/xml-sax-machines/builder.rb', line 27

def document
  @document
end

Instance Method Details

#cdata_block(string) ⇒ Object

:nodoc:



60
61
62
63
# File 'lib/xml-sax-machines/builder.rb', line 60

def cdata_block(string) #:nodoc:
  super
  @context.add_child(Nokogiri::XML::CDATA.new(@document, string))
end

#characters(string) ⇒ Object

:nodoc:



49
50
51
52
53
54
55
56
57
58
# File 'lib/xml-sax-machines/builder.rb', line 49

def characters(string) #:nodoc:
  super
  # http://nokogiri.lighthouseapp.com/projects/19607-nokogiri/tickets/68-xpath-incorrect-when-text-siblings-exist#ticket-68-1
  sibling = @context.children.last
  if sibling.kind_of?(Nokogiri::XML::Text)
    sibling.content += string
  else
    @context.add_child(Nokogiri::XML::Text.new(string, @document))
  end
end

#comment(string) ⇒ Object

:nodoc:



65
66
67
68
# File 'lib/xml-sax-machines/builder.rb', line 65

def comment(string) #:nodoc:
  super
  @context.add_child(Nokogiri::XML::Comment.new(@document, string))
end

#end_element(name) ⇒ Object

:nodoc:



42
43
44
45
46
47
# File 'lib/xml-sax-machines/builder.rb', line 42

def end_element(name) #:nodoc:
  super
  raise "Unmatched closing element. Got '#{name}' but expected '#{@context.name}'" \
    unless name == @context.name
  @context = @context.parent
end

#start_documentObject

:nodoc:



29
30
31
32
33
# File 'lib/xml-sax-machines/builder.rb', line 29

def start_document #:nodoc:
  super
  @document = Nokogiri::XML::Document.new
  @context  = @document
end

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

:nodoc:



35
36
37
38
39
40
# File 'lib/xml-sax-machines/builder.rb', line 35

def start_element(name, attributes = []) #:nodoc:
  super
  el = Nokogiri::XML::Element.new(name, @document)
  Hash[*attributes.flatten].each_pair{|k, v| el[k] = v}
  @context = @context.add_child(el)
end