2

I have the following XML

<CallResult>
  <Success>true</Success>
  <Result>
    <ZoneInfo>
      <Id>3</Id>
      <Name>test-room</Name>
      <NId>sdfsdg</NId>
    </ZoneInfo>
    <ZoneInfo>
      <Id>16</Id>
      <Name>Dynamic</Name>
      <NId>sadadrwed543th</NId>
    </ZoneInfo>
    <ZoneInfo>
      <Id>32</Id>
      <Name>lobby</Name>
      <NId>ssdfrgfdfg</NId>
    </ZoneInfo>
    <ZoneInfo>
      <Id>33</Id>
      <Name>conf</Name>
      <NId>sdfsfewr232f</NId>
    </ZoneInfo>
  </Result>
  <Message>Success</Message>
</CallResult>

I am trying to parse the XML so that each different 'ZoneInfo' attributes is a hash in an array.

E.g.

Zones[0] = Hash[Id => 32, Name => lobby, NId => ssdfrgfdfg]

Zones[1] = Hash[Id => 33, Name => conf, NId => sdfsfewr232f] etc...

My limited XML parsing knowledge has come a croper. All I really know is how to extract a single element. E.g.

doc = REXML::Document.new(xmlData)
doc.elements.each("CallResult/Success") do |ele|
  p ele.text;
end

Could someone help with some more info on how to loop through just extracting info from each 'ZoneInfo' element?

Thanks

2 Answers 2

2

I use another gem 'nokogiri', maybe the best gem to parse HTML/XML now.

require 'nokogiri'

str = "<CallResult> ......"
doc = Nokogiri.XML(str)
Zones = []
doc.xpath('//ZoneInfo').each do |zone|
  Zones << { "Id" => zone.xpath('Id').text, "Name" => zone.xpath('Name').text, "NId" => zone.xpath("NId").text}
end
Sign up to request clarification or add additional context in comments.

Comments

2

You just need to use nori gem

require 'nori'
your_hash = Nori.parse(your_xml)

And then it should be straightforward to convert this nested hash to an array of hashes if you need to store your data that way.

If you need more info, api doc is here - http://rubydoc.info/gems/nori/1.1.3/frames

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.