I want to open an external XML file, parse it and use the data to store in my database. I do this with Nokogiri quite easily:
file = '...external.xml' xml = Nokogiri::XML(open(file)) xml.xpath('//Element').each do |element| # process elements and save to Database e.g.: @data = Model.new(:attr => element.at('foo').text) @data.save end
Now I want to try (possibly faster) Ox gem ( https://github.com/ohler55/ox ) - but I don’t understand how to open and process a file from a documentary.
Any equivalent code examples for the above code would be great! Thank!
You cannot use XPath to search for nodes in Ox, but Ox provides a method locate. You can use it like this:
locate
xml = Ox.parse(%Q{ <root> <Element> <foo>ex1</foo> </Element> <Element> <foo>ex2</foo> </Element> </root> }.strip) xml.locate('Element/foo/^Text').each do |t| @data = Model.new(:attr => t) @data.save end # or if you need to do other stuff with the element first xml.locate('Element').each do |elem| # do stuff @data = Model.new(:attr => elem.locate('foo/^Text').first) @data.save end
, . locate . element.rb.
:
doc2 = Ox.parse(xml)
Ruby, xml = IO.read('filename.xml') ( ). :
xml = IO.read('filename.xml')
doc = Ox.parse(IO.read(filename))
XML UTF-8, :
doc = Ox.parse( File.open(filename,"r:UTF-8",&:read) )