Nokogiri Xml Parsing

Q: How to parse Xml Document with Nokogiri?

Answer: In model:

1) Put this line in your gem file.

 gem 'nokogiri'

2) Require these after installing nokogiri gem in you project.

require 'open-uri' # required for this
require 'net/http' # not for this its used in my project
require 'uri'#not required for this [Its just used in my project]
require 'rubygems' #no need of it in rails project as Gems are automatically loaded.
require 'nokogiri' #no need of it in rails project as Gems are automatically loaded.

3) Write this method in your model

def self.xml_parser
    xml_string = open("#{Rails.root}/abc.xml").read
    root = Nokogiri::XML(xml_string)
    hotels = root.xpath("hotels/hotel")
    hotels.each do |hotel|
    hotel_hash = {
        name: hotel.at_xpath("hotel_name").text,
        telephone_no:  hotel.at_xpath("hotel_phone_number").text,
        latitude: hotel.at_xpath("hotel_latitude").text,
        longitude: hotel.at_xpath("hotel_longitude").text,
        email: hotel.at_xpath("hotel_email").text
        hotel_record = Hotel.create!(hotel_hash)


4) In rails console call this



I am Senior Software Engineer. I love reading, writing, sharing,developing, hiking, movies, trips, mountains, brooks, hills etc.

Tagged with: , ,
Posted in Nokogiri
2 comments on “Nokogiri Xml Parsing
  1. It would be helpful to see the xml document you are using to get your data from

  2. taimoor.changaiz says:

    The code speaks for itself. If you see this line `hotels = root.xpath(“hotels/hotel”)`. It means root element is hotels and it have many nested elements which are named as hotel. In this way you can see that each hotel has child elements (hotel_name, hotel_email etc).

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: