Class: Peanuts::XML::LibXML::Reader

Inherits:
Reader
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/peanuts/xml/libxml.rb

Constant Summary collapse

SCHEMAS =
{:xml_schema => :schema, :relax_ng => :relax_ng}
RD =
::LibXML::XML::Reader
NODE_TYPES =
[
  nil,
  :element,
  :attribute,
  :text,
  :cdata,
  :entity_reference,
  :entity,
  :processing_instruction,
  :comment,
  :document,
  :document_type,
  :document_fragment,
  :notation,
  :whitespace,
  :significant_whitespace,
  :end_element,
  :end_entity,
  :xml_declaration
].freeze
DEFAULT_OPTIONS =
{}

Instance Method Summary collapse

Methods inherited from Reader

new

Constructor Details

#initialize(source, options = {}) ⇒ Reader

Returns a new instance of Reader.



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/peanuts/xml/libxml.rb', line 126

def initialize(source, options = {})
  super()
  options = options.dup
  @schema = options.delete(:schema)
  options = LibXML.libxml_opt(options, DEFAULT_OPTIONS)
  @reader = case source
  when String
    RD.string(source.to_s, options)
  when URI
    RD.file(source.to_s, options)
  when ::LibXML::XML::Document
    RD.document(source)
  else
    raise "unsupported source #{source.inspect}" unless source.respond_to?(:read)
    RD.io(source, options)
  end
  @reader.send("#{SCHEMAS[schema.type]}_validate", schema.schema) if @schema
end

Instance Method Details

#closeObject



145
146
147
# File 'lib/peanuts/xml/libxml.rb', line 145

def close
  @reader.close
end

#eachObject



164
165
166
167
168
169
170
171
172
# File 'lib/peanuts/xml/libxml.rb', line 164

def each
  depth = self.depth
  if read
    while self.depth > depth
      yield self
      break unless next_sibling
    end
  end
end

#find_elementObject



174
175
176
177
178
179
# File 'lib/peanuts/xml/libxml.rb', line 174

def find_element
  until @reader.node_type == RD::TYPE_ELEMENT
    return nil unless read
  end
  self
end

#node_typeObject



151
152
153
# File 'lib/peanuts/xml/libxml.rb', line 151

def node_type
  NODE_TYPES[@reader.node_type]
end

#valueObject



155
156
157
158
159
160
161
162
# File 'lib/peanuts/xml/libxml.rb', line 155

def value
  case @reader.node_type
  when RD::TYPE_ELEMENT
    _string(@reader.read_string)
  else
    @reader.has_value? ? _string(@reader.value) : nil
  end
end