0

I am trying to convert XML with Nokogiri to a hash:

<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 won't work cause that only returns result once.

How do I get the right names from the child nodes?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Hans de Jong
  • 2,030
  • 6
  • 35
  • 55
  • I just notised the lenght of xml.xpath('//result') is onyl 1. so also the question arises is how to loop over the childs – Hans de Jong May 01 '16 at 12:07
  • 1
    Use `...xpath('//result/*')...` ? – har07 May 01 '16 at 12:08
  • Aah, yes that works. thanks a lot! – Hans de Jong May 01 '16 at 12:11
  • converted my comment to answer with a brief explanation of what the XPath do exactly – har07 May 01 '16 at 12:31
  • 1
    See also [my answer](http://stackoverflow.com/a/10144623/405017) to [Convert a Nokogiri document to a Ruby Hash](http://stackoverflow.com/questions/1230741/convert-a-nokogiri-document-to-a-ruby-hash?rq=1) for a small-yet-robust implementation for serializing any Nokogiri document to a Hash. – Phrogz May 02 '16 at 18:01

1 Answers1

2

"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|
har07
  • 88,338
  • 12
  • 84
  • 137