views:

69

answers:

1

Hi All, I found this interesting post explaining how to use saxparser for large xml files in ruby http://www.ioncannon.net/programming/643/fast-xml-parsing-with-ruby/ I would like to use the line : parser = XML::SaxParser.file("posts.xml") in one of my controllers, but instead of a file I have an xml post from another app, can anyone help with the syntax? Thanks a lot

+1  A: 

I'm a ruby noob, but give this a try.

Custom class file for parsing:

require 'rubygems'
require 'xml/libxml'
require 'handler'

class SaxParser
  def initialize(xml)
    @parser = XML::SaxParser.new
    @parser.string = xml
    @parser.callbacks = Handler.new
  end

  def parse
    @parser.parse
    @parser.callbacks.elements
  end
end

Now in the file you would like to parse the XML:

# reference your custom class
require 'sax_parser'

xml = "your xml string"

# parse xml
parsedXml = SaxParser.new(xml).parse

The code above was stolen from this post on Luca Guidi's blog.

Nate Pinchot
Thanks Nate, just what I looking for
El man