That isn??™t possible with REXML.
CHAPTER 8 ?– CONTENT RENDERING 147
Java SAX Parsing
The SAX API is much more useful in situations where you have a large input to handle, and
don??™t need to keep it all in memory. For example, say you??™re collecting specific parts of data
but don??™t care about the whole thing. SAX is a stream-based API, which means the different
parts of the XML document are made available to you sequentially.
In Java, the easiest way to handle SAX events is by creating a subclass of DefaultHandler,
and overriding the methods that provide interesting information. This means it won??™t be easy
to make it have exactly the same output as the other examples, but we??™ll try to get it as close
as possible. The large difference will be text handling, because there??™s no way to get the text
inside an element until after it has been parsed.
require 'java'
class PrintHandler < org.xml.sax.helpers.DefaultHandler
def initialize
@indent = 0
@text = ""
end
def characters(ch, start, length)
@text << java.lang.String.new(ch,start,length).to_s
end
def startElement(uri,name,qname,attrs)
print " "*@indent
print name
if attrs.getLength > 0
print ":"
for i in 0...(attrs.getLength)
print " #{attrs.getLocalName(i)}=>#{attrs.getValue(i)}"
end
end
puts
@indent+=2
end
def endElement(uri,name,qname)
if @text.strip.length > 0
print " "*@indent
puts "::#{@text.strip}"
@text = ''
end
@indent-=2
end
end
xr = org.xml.sax.helpers.
Pages:
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239