Hans de Jong Hans de Jong - 7 months ago 29
Ruby Question

ruby converting nokogiri xml to hash

I am trying to convert a XML that I got with the help of nokogiri to a bit easier workable hash (keep in mind I am a bit new to ruby please)

<eveapi version="2">
<currentTime>2016-05-01 11:38:14</currentTime>
<result>
<characterID>93898118</characterID>
<characterName>Ghitzarai</characterName>
<race>Minmatar</race>
<bloodlineID>4</bloodlineID>
<bloodline>Brutor</bloodline>
<ancestryID>24</ancestryID>
<ancestry>Slave Child</ancestry>
<corporationID>98012663</corporationID>
<corporation>Dry Atomic Fusion</corporation>
</result>
</eveapi>

# asume xml is the above XML
hash = {}
xml.xpath('//result').each do |row|
hash[get_node_name:] = row.content
end


now row.name wont work cause that only returns result once.
How to get the right names from the child nodes?

Answer

"now row.name wont work cause that only returns result once. How to get the right names from the child nodes?"

Add /* after result to get all child elements of <result> regardless of the child element name :

xml.xpath('//result/*').each do |row|
Comments