Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- jruby, a ruby interpreter written in java, makes it much easier to
- interface with java libraries from ruby than the ruby java bridge
- (where i couldnt, for the life of me, make java accept a pure ruby
- java.io.InputStream implementation). I chose woodstox's implementation
- of stax (a pull parser that apparently performs better than even the
- xerces stream parser) to play with the idea.
- As an aside, doesn't the idea of controlling the flow of the parser
- programmatically (by calling 'next' on the reader to get an event)
- make so much more sense than having the entire flow of your code
- controlled by an xml file?
- #!/usr/bin/env jruby
- #
- # Created by Travis Tilley on 2006-12-09.
- # Copyright (c) 2006. All rights reserved.
- require 'java'
- # this class can wrap a generic ruby IO duck and make it quack like an
- InputStream
- include_class 'org.jruby.util.IOInputStream'
- # stax
- include_class 'javax.xml.stream.XMLInputFactory'
- include_class 'javax.xml.stream.XMLStreamException'
- include_class 'javax.xml.stream.XMLStreamReader'
- # the java interface for accessing XMLStreamConstants doesnt like me
- XMLStreamConstants = {
- :START_ELEMENT => 1,
- :END_ELEMENT => 2,
- :PROCESSING_INSTRUCTION => 3,
- :CHARACTERS => 4,
- :COMMENT => 5,
- :SPACE => 6,
- :START_DOCUMENT => 7,
- :END_DOCUMENT => 8,
- :ENTITY_REFERENCE => 9,
- :ATTRIBUTE => 10,
- :DTD => 11,
- :CDATA => 12,
- :NAMESPACE => 13,
- :NOTATION_DECLARATION => 14,
- :ENTITY_DECLARATION => 15
- }
- # create a standard ruby File object
- xml = File.new('tst.xml')
- # create InputStream interface to the IO object
- xmlstream = IOInputStream.new(xml)
- # create a stax stream reader and hook it to the InputStream
- factory = XMLInputFactory.newInstance
- reader = factory.createXMLStreamReader(xmlstream)
- # implement a "stream parser" on top of the pull parser (kinda)
- event = reader.getEventType
- while event
- case event
- when XMLStreamConstants[:START_DOCUMENT]
- puts "Start Document"
- when XMLStreamConstants[:START_ELEMENT]
- puts "Start Element: " + reader.getLocalName
- reader.getAttributeCount.times do |count|
- puts " Attribute: " + reader.getAttributeLocalName(count)
- puts " -> Value: " + reader.getAttributeValue(count)
- end
- when XMLStreamConstants[:CHARACTERS]
- puts "Text: " + reader.getText if ! reader.isWhiteSpace
- when XMLStreamConstants[:END_ELEMENT]
- puts "End Element: " + reader.getLocalName
- when XMLStreamConstants[:END_DOCUMENT]
- puts "End Document"
- end
- if reader.hasNext
- event = reader.next
- else
- event = nil
- end
- end
Add Comment
Please, Sign In to add comment