How to access a xml thourgh Ruby on rails


#1

Hi to everyone,

   I am getting xml in the below format
123

FirstSecondThird

FirstSecondThird

FirstSecondThird

I have to store this xml in my table sample which contain the fields as
id,first,second,third,child1,child2 and
child3,all are string fields except id field

and my record structure to be

id first second third child1 child2
child3

1 1 2 3 First Second
Third
2 1 2 3 First Second
Third
3 1 2 3 First
Second Third

Can any One tell me how to acheive this

I tried with XMLSimple,Rexml or even with Hashs

With XMLSimple Some garbage getting inserted into the table along with
the
value
through hashes I can access each element and put in that table object
but I’m getting Hashes which includes array also So for 3 entries we
can do
but it is large process for more records (accessing each element). And
not a
feasible solution also

Please help me how can I acheive these


#2

Have you tried Nokogiri? You can access elements through XPath and
iterate over them easily:

require ‘nokogiri’

xml_doc = Nokogiri::XML(@string_with_your_xml)
grn_elements = xml_doc.xpath(’//grn’)
arn_elements = xml_doc.xpath(’//arn’)
arn_elements[0].children each do |child|
puts “Name: #{child.name} Value: #{child.inner_text}”
end


#3

Thank you

But it is trowing the error as

NoMethodError: undefined method `each’ for #<Nokogiri::XML::Element:
0x45146a0>

when i try with each

is there any way to access the arn_elements[0].children ?

On Jan 29, 5:59 pm, Bosko I. removed_email_address@domain.invalid