Class: Moxml::Context

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(adapter = nil) ⇒ Context

Returns a new instance of Context.



7
8
9
# File 'lib/moxml/context.rb', line 7

def initialize(adapter = nil)
  @config = Config.new(adapter)
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



5
6
7
# File 'lib/moxml/context.rb', line 5

def config
  @config
end

Instance Method Details

#create_document(native_doc = nil) ⇒ Object



11
12
13
# File 'lib/moxml/context.rb', line 11

def create_document(native_doc = nil)
  Document.new(config.adapter.create_document(native_doc), self)
end

#parse(xml, options = {}) ⇒ Object



15
16
17
# File 'lib/moxml/context.rb', line 15

def parse(xml, options = {})
  config.adapter.parse(xml, default_options.merge(options))
end

#sax_parse(xml, handler = nil) {|block| ... } ⇒ void

This method returns an undefined value.

Parse XML using SAX (event-driven) parsing

SAX parsing is memory-efficient and suitable for large XML files. Provide either a handler object or a block with DSL.

Examples:

With handler object

handler = MyHandler.new
context.sax_parse(xml_string, handler)

With block

context.sax_parse(xml_string) do
  start_element { |name, attrs| puts name }
  characters { |text| puts text }
end

Parameters:

  • xml (String, IO)

    XML string or IO object to parse

  • handler (Moxml::SAX::Handler, nil) (defaults to: nil)

    Handler object (optional if block given)

Yields:

  • (block)

    DSL block for defining handlers (optional if handler given)

Raises:

  • (ArgumentError)

    if neither handler nor block is provided



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/moxml/context.rb', line 40

def sax_parse(xml, handler = nil, &block)
  # Load SAX module if not already loaded
  require_relative "sax" unless defined?(Moxml::SAX)

  # Create block handler if block given
  handler ||= SAX::BlockHandler.new(&block) if block

  # Validate handler
  raise ArgumentError, "Handler or block required" unless handler
  unless handler.is_a?(SAX::Handler)
    raise ArgumentError, "Handler must inherit from Moxml::SAX::Handler"
  end

  # Delegate to adapter
  config.adapter.sax_parse(xml, handler)
end