How to search an XML when parsing it using SAX in nokogiri

Posted by ralph on Stack Overflow See other posts from Stack Overflow or by ralph
Published on 2010-12-27T01:45:06Z Indexed on 2010/12/27 1:54 UTC
Read the original article Hit count: 535

Filed under:
|
|

I have a simple but huge xml file like below. I want to parse it using SAX and only print out text between the title tag.

<root>
    <site>some site</site>
    <title>good title</title>
</root>

I have the following code:

require 'rubygems'
require 'nokogiri'
include Nokogiri

class PostCallbacks < XML::SAX::Document
  def start_element(element, attributes)
    if element == 'title'
      puts "found title"
    end
  end

  def characters(text)
    puts text
  end
end

parser = XML::SAX::Parser.new(PostCallbacks.new)
parser.parse_file("myfile.xml")

problem is that it prints text between all the tags. How can I just print text between the title tag?

© Stack Overflow or respective owner

Related posts about ruby

Related posts about nokogiri