-1

Is it possible to parse and store an xml file root attributes in Nokogiri SAX parser?

How do one get the id-value and expires-value in the root-element?:

<root id="01" expires="2010-10-01">
  <aaa>Text</aaa>
  <bbb>Text</bbb>
</root>

2 Answers2

2

Like @luis.parravicini said, *start_element is called for every tag parsed. As for the root element, it'll be on the first call to that method.*

So I did something like this:

class MyDocument < Nokogiri::XML::SAX::Document
  def initialize
   @infodata = {}
  end

  def start_element name, attrs = []
   @attrs = attrs
   @content = ''

    if name == 'rootname'
       @infodata[:id] = Hash[@attrs]["id"]
       @content = ''
     end
   end
end
1

Nokogiri documentation gives you an example on how to parse xml using the sax parser and obtain what you need. Take a look here: http://nokogiri.org/Nokogiri/XML/SAX/Document.html

luis.parravicini
  • 1,214
  • 11
  • 19
  • Yeah I know, I know how to use all those methods. But there is no documentation on how to get a root element when sax parsing. –  Apr 16 '12 at 13:05
  • 2
    _start_element_ is called for every tag parsed. As for the root element, it'll be on the first call to that method. Try the sample code with your xml. – luis.parravicini Apr 16 '12 at 13:13