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
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
- Code for this article: code.tgz
- REXML website
- REXML API documentation
- Ruby-lang website
- Some IRB tips
- xml file has illegal character
2006-04-21 10:18:31 gervasegallant - xml file has illegal character
2006-04-21 10:20:13 gervasegallant - Unspported encoding
2005-11-14 12:15:25 jamesgbritt - Unspported encoding
2005-11-22 14:32:10 KoenVervloesem