简体   繁体   中英

Accessing Hash of Hash of Hash in Ruby

I'm attempting to grab event log entries which are passed in xlm, convert them into a hash and then store into a database.

I'm currently using the XmlSimple gem to convert the xml input into a hash.

Test sample input:

require 'xmlsimple'

h = XmlSimple.xml_in('
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
  <System>
    <Provider Name="Service Control Manager" Guid="{555908d1-a6d7-4695-8e1e-26931d2012f4}" EventSourceName="Service Control Manager" />
  </System>
</Event>
', { 'KeyAttr' => 'name' })


puts "#{h}"

This returns:

{"xmlns"=>"http://schemas.microsoft.com/win/2004/08/events/event", "System"=>[{"Provider"=>[{"Name"=>"Service Control Manager", "Guid"=>"{555908d1-a6d7-4695-8e1e-26931d2012f4}", "EventSourceName"=>"Service Control Manager"}]}]}

How can I access the System Provider GUID?

I can return all of the System elements by doing:

puts "#{h['System']}"

However

puts "#{h['System']['Provider'}"

Returns:

can't convert String into Integer (TypeError)

I've tried casting the result to a string with no luck. Do I have the XmlSimple formatting wrong? Am I accessing the wrong key? Is there another way to do this?

Thanks for any help!

It looks like you're just missing a closing ] . Hashes should nest arbitrarily deep without problem.

h['System'] is an Array. Use:

h['System'][0]['Provider']

The [] at the beginning of the "System" denotes that its value is an array of hashes. You can do this:

puts "#{h['System'][0]['Provider'}"

at the same time "Provider" itself is an array, so you would have to do the same for it, for instance:

puts "#{h['System'][0]['Provider'][0]['Guid']"

小心阵列

h["System"].first["Provider"].first["Guid"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM