Created
April 24, 2012 07:26
-
-
Save soulcutter/2477448 to your computer and use it in GitHub Desktop.
Saxerator example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'saxerator' | |
# The parser takes any IO object (or String) - a File is a common choice | |
parser = Saxerator.parser(bookshelf_xml) | |
# Simplest usage, parses every <book></book> in the document | |
parser.for_tag(:book).each do |book| | |
# Your book hash might look something like | |
{ 'title' => 'Rails 3 In Action', 'author' => ['Ryan Bigg', 'Yehuda Katz'] } | |
end | |
# You can chain predicates | |
parser.for_tag(:book).within(:bookshelf).each do |book| | |
# ... | |
end | |
# You can re-use intermediary predicates | |
bookshelf_contents = parser.within(:bookshelf) | |
books = bookshelf_contents.for_tag(:book) | |
magazines = bookshelf_contents.for_tag(:magazine) | |
# nothing actually gets parsed until you call an Enumerable method | |
# You can use other Enumerable methods as well | |
puts "First title: #{parser.for_tag(:title).first}" | |
# If you want you can get the entire document | |
parser.all # big, giant hash |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment