XML.com: XML From the Inside Out
oreilly.comSafari Bookshelf.Conferences.

advertisement

REXML: Processing XML in Ruby
by Koen Vervloesem | Pages: 1, 2, 3, 4, 5

Stream Parsing

Stream parsing is faster than tree parsing. If speed matters, the stream parser can be handy. However, features such as XPath are not available. You have to supply a listener class and each time REXML encounters an event (start tag, end tag, text, etc.), the listener will be notified of the event. An example program:

Listing 4: The Stream Parser in Action (code3.rb)

require 'rexml/document'
require 'rexml/streamlistener'
include REXML

class Listener
  include StreamListener
  def tag_start(name, attributes)
    puts "Start #{name}"
  end
  def tag_end(name)
    puts "End #{name}"
  end
end

listener = Listener.new
parser = Parsers::StreamParser.new(File.new("bibliography2.xml"), listener)
parser.parse

The file bibliography2.xml is the following:

Listing 5: The bibliography2.xml File

bibliography2.xml

Running code3.rb gives this output:

koan$ ruby code3.rb 
Start bibliography
Start biblioentry
Start author
Start firstname
End firstname
Start surname
End surname
End author
Start title
End title
Start publisher
Start publishername
End publishername
End publisher
Start pubdate
End pubdate
End biblioentry
End bibliography

In Conclusion

Ruby and XML make a great team. The REXML XML processor allows one to create, access, and modify XML documents in a very intuitive way. With the help of Ruby's interactive debugger irb, we can also explore XML documents very easily.

Related Links



1 to 2 of 2
  1. xml file has illegal character
    2006-04-21 10:18:31 gervasegallant
  2. Unspported encoding
    2005-11-14 12:15:25 jamesgbritt
1 to 2 of 2