RExpat - Ruby Extension module for the Expat

This RubyGem is a Ruby extension module to access the Expat (XML Parser Toolkit; James Clark’s home page), written by James Clark.

This is a fork of the xmlparser gem created by 吉田正人 (Yoshida Masato), in the aim of supporting newer Expat and Ruby versions and polishing the API design. The goal is not to be a drop-in replacement of the gem, but a lean wrapper implementation.

Installation

Prerequisites:

Install the gem and add to the application’s Gemfile by executing:

bundle add rexpat

If bundler is not being used to manage dependencies, install the gem by executing:

gem install rexpat

This gem uses the mkmf gem, so you can provide some options for Expat locations:

gem install rexpat -- \
    --with-expat-include=/path/to/expat/include \
    --with-expat-lib=/path/to/expat/lib

Usage

To load the library:

require 'rexpat'

To get the parse results, you have to define various event handlers. The approach is like Simple API for XML (SAX) style. You can make a subclass of the RExpat class and define event handler methods in it, or define singleton methods for instances of the RExpat class. If no event handlers defined, it only checks the grammer. For example:

class MyParser < RExpat
  def on_start_element(name, attrs)
    puts "name is #{name}" \
         "and attributes are #{attrs.inspect}"
  end
end

parser = MyParser.new

# # or
# parser = RExpat.new
# parser.define_singleton_method(:on_start_element) do |name, attrs|
#   puts "name is #{name}" \
#        "and attributes are #{attrs.inspect}"
# end

parser.parse('<root foo="bar"/>')

This gem supports UTF-8 and UTF-16 as input character encodings. The output is in UTF-8.

See also the API documentation.

Differences with the xmlparser gem

This gem dropped the support for custom encodings. If you are interested in it, we welcome patches. Please also refer to the official article, “Writing A Custom Encoding”. Note that providing a flexible Ruby interface to customize the encoding mapping on “unknown encoding” events has been considerably inefficient and easily become errorprone.

This gem dropped the support for iterator APIs. It might be implemented in the future, but in pure Ruby (rather than in C) on top of the current bindings.

Contributing

Bug reports and pull requests are welcome.

License

Copyright © 2013 吉田正人
Copyright © 2026 gemmaro

It is licensed under the Ruby license (see licenses/Ruby-license.txt) or the Expat license (that is, MIT license; see licenses/Expat-license.txt).