Read XML file using Hpricot in Rails

Here is a small post on how to read an xml file using Hpricot in your Rails application.

First of all you need to install hpricot with the following command

gem install hpricot

Here is a sample xml file which I want to read. You can just paste the following code and create .xml  file

<profiles>

<profile>
<name> test </name>

<user_ids>
<user_id>39</user_id>
</user_ids>
</profile>

<profile>
<name> test 123</name>

<user_ids>
<user_id>39</user_id>
<user_id>46</user_id>
</user_ids>
</profile>
</profiles>

Now here comes the code to read this file. Don’t forget to add require ‘hpricot’ in the controller where you are putting this code.

test = Hpricot::XML(File.open(“test.xml”, “r”))

(test/:profile).each do |pro| render :text=>(((pro.at(“name”).innerHTML.strip).to_s)+”=>”+(pro.at(“   _id”).innerHTML.strip).to_s).inspect and return false
end

Remove .inspect and return false once u get the required output

Hope this helps. If you have any doubts just post a message and I will try to reply.

Be Sociable, Share!

Leave a Reply

Your email address will not be published. Required fields are marked *