/sax-machine

A declarative sax parsing library backed by Nokogiri.

Primary LanguageRuby

SAX Machine

http://github.com/pauldix/sax-machine/wikis

http://github.com/pauldix/sax-machine/tree/master

Description

A declarative SAX parsing library backed by Nokogiri

Usage

require 'sax-machine'

# Class for parsing an atom entry out of a feedburner atom feed
class AtomEntry
  include SAXMachine
  element :title
  # the :as argument makes this available through atom_entry.author instead of .name
  element :name, :as => :author
  element "feedburner:origLink", :as => :url
  element :summary
  element :content
  element :published
end

# Class for parsing Atom feeds
class Atom
  include SAXMachine
  element :title
  # the :with argument means that you only match a link tag that has an attribute of :type => "text/html"
  # the :value argument means that instead of setting the value to the text between the tag,
  # it sets it to the attribute value of :href
  element :link, :value => :href, :as => :url, :with => {:type => "text/html"}
  element :link, :value => :href, :as => :feed_url, :with => {:type => "application/atom+xml"}
  elements :entry, :as => :entries, :class => AtomEntry
end

# you can then parse like this
feed = Atom.parse(xml_text)
# then you're ready to rock
feed.title # => whatever the title of the blog is
feed.url # => the main url of the blog
feed.feed_url # => goes to the feedburner feed
 
feed.entries.first.title # => title of the first entry
feed.entries.first.author # => the author of the first entry
feed.entries.first.url # => the permalink on the blog for this entry
# etc ...

# you can also use the elements method without specifying a class like so
class SomeServiceResponse
  elements :message, :as => :messages
end

response = SomeServiceResponse.parse("<response><message>hi</message><message>world</message></response>")
response.messages.first # => "hi"
response.messages.last  # => "world"

attribute and value

    class AuthorElement
      include SAXMachine
      value :name
      attribute :role
    end
    class ItemElement
      include SAXMachine
      element :title
      elements :author, :as => :authors, :class => AuthorElement
    end

    item = ItemElement.parse(xml = <<-XML)
      <item id="1">
        <title>sweet</title>
        <author role="writer">John Doe</author>
        <author role="artist">Jane Doe</author>
      </item>
    XML

    item.title # => 'sweet'
    item.authors.first.name # => 'John Doe'
    item.authors.last.role # => 'artist'

    class AuthorRoles
      include SAXMachine
      elements :author, :as => :roles, :value => :role
    end

    AuthorRoles.parse(xml = <<-XML).parse.roles # => ['writer', 'artist']

Laziness/Enumerator – Constant memory usage

The Nokogiri Sax parser already operates in constant memory with respect to the file contents. However, Sax Machine fills up memory as it creates your Ruby objects. Using the laziness option will parse top-level elements one at a time- allowing for constant memory usage with respect to the Ruby objects.
The lazy option only allows one set of elements to be declared as lazy.

class Atom
  include SAXMachine
  element :title
  elements :entry, :lazy => true, :as => :entries, :class => AtomEntry
end

feed = Atom.parse(xml_file_handle, :lazy => true)
feed.entries # => #<Enumerator: #<Enumerator::Generator:0x00000004c41ea0>:each> 
feed.entries.each do |entry|
  # every time the block is called the next entry is parsed- no memory blow up!
  #
  # This is probably where you save the entry to a database
end

Warning !!!

  • If you use the lazy option twice, or if the class using this laziness is referenced from multiple other classes, the behavior will be incorrect.
  • Does not work with Ruby version 1.8. Uses ruby fibers and Enumerator capabilities, both of which were added in Ruby version 1.9.

Caution

  • The overall speed with laziness may be slower if you can already fit everything into memory.
  • Once you traverse an enumerator (with #each), it will be empty.

LICENSE

(The MIT License)

Copyright © 2009:

Paul Dix

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
‘Software’), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.