Learner
Learner

Reputation: 59

How to extract an XML tag ID and its value in Ruby from an XML document

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.

Upvotes: 0

Views: 1539

Answers (1)

hek2mgl
hek2mgl

Reputation: 158130

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"}

Upvotes: 1

Related Questions