0

Consider a XML document

<string id = "id1" ><p> Text1 </p></string>
<string id = "id2" > Text2 </string>

I want to parse this document in ruby and make a hash like {id:"Text1", "id2":Text2}

I tried nokogiri and REXML tutorials but was not much useful. Can someone suggest me the way to do it.

August
  • 12,410
  • 3
  • 35
  • 51
Learner
  • 59
  • 8

1 Answers1

1

It isn't possible to achieve the desired result in a single xpath query. You can select and iterate over all the string nodes and extract information like this:

require 'nokogiri'

doc = Nokogiri::XML(File.open("example.xml"));

result = {}
doc.xpath("//string").each do |node|
    id = node.get_attribute "id"
    text = node.inner_text.strip!
    result[id] = text
end

puts result

Output:

{"id1"=>"Text1", "id2"=>"Text2"}
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • This code is giving nil values for those string tags having only one line text. But it is giving perfect output for the string tags having more than one line text. Not able to figure out the reason behind it – Learner Jul 30 '14 at 13:13
  • @Learner Can't reproduce this – hek2mgl Jul 30 '14 at 16:08