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_PARSER_OPTIONS =
{
  :libxml_encoding => ::LibXML::XML::Encoding::UTF_8,
  :libxml_options => ::LibXML::XML::Parser::Options::NOENT
}

Instance Method Summary collapse

Methods inherited from Reader

method_missing, new

Constructor Details

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

Returns a new instance of Reader.



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/peanuts/xml/libxml.rb', line 106

def initialize(source, source_type, options = {})
  super()
  options = options.dup
  @schema = options.delete(:schema)
  @reader = case source_type
  when :string
    RD.string(source, parser_opt(options))
  when :io
    RD.io(source, parser_opt(options))
  when :uri
    RD.file(source, parser_opt(options))
  when :document
    RD.document(source)
  else
    raise ArgumentError, "unrecognized source type #{source_type}"
  end
  @reader.send("#{SCHEMAS[schema.type]}_validate", schema.schema) if @schema
end

Instance Method Details

#closeObject



125
126
127
# File 'lib/peanuts/xml/libxml.rb', line 125

def close
  @reader.close
end

#eachObject



144
145
146
147
148
149
150
151
152
# File 'lib/peanuts/xml/libxml.rb', line 144

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

#find_elementObject



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

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

#node_typeObject



131
132
133
# File 'lib/peanuts/xml/libxml.rb', line 131

def node_type
  NODE_TYPES[@reader.node_type]
end

#valueObject



135
136
137
138
139
140
141
142
# File 'lib/peanuts/xml/libxml.rb', line 135

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