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
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/moxml/context.rb', line 15

def parse(xml, options = {})
  # Detect if input has XML declaration
  xml_string = if xml.respond_to?(:read)
                 xml.read.tap do
                   xml.rewind if xml.respond_to?(:rewind)
                 end
               else
                 xml.to_s
               end
  has_declaration = xml_string.strip.start_with?("<?xml")

  # Parse with adapter (without declaration info - adapters don't need it)
  parsed_options = default_options.merge(options)
  doc = config.adapter.parse(xml_string, parsed_options)

  # Set declaration flag on Document wrapper (proper OOP)
  doc.has_xml_declaration = has_declaration if doc.is_a?(Document)

  doc
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



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/moxml/context.rb', line 57

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