开发者

Ruby SaxParser Syntax

开发者 https://www.devze.com 2023-01-03 20:47 出处:网络
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 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开发者_StackOverflow中文版 xml post from another app, can anyone help with the syntax? Thanks a lot


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消