0

i have the following xml:

        <key>Some Text</key>
        <string>Some Content</string>
        <key>Some Text</key>
        <string>Some Content</string>
        <key>Some Text</key>
        <string>Some Content</string>
        <key>Some Text</key>
        <string>Some Content</string>
        <key>Some Text</key>
        <string>Some Content</string>
        <key>Some Text</key>
        <string>Some Content</string>
        <key>Some Text</key>
        <integer>1</integer>
        <key>Some Text</key>
        <true/>
        <key>Some Text</key>
        <true/>
        <key>Some Text</key>
        <integer>6</integer>
        <key>Some Text</key>
        <true/>

How do i have to configure the Ruby XMLSimple gem to get a Hash with key / value? Or is XMLSimple the wrong tool?

Thanks for your help!

mu is too short
  • 426,620
  • 70
  • 833
  • 800
noOne
  • 1

1 Answers1

1

I'm not sure about XMLSimple but you could use Nokogiri. Something like this should do the trick:

def unpack_value(node)
    return node.text      if(node.node_name == 'string')
    return node.text.to_i if(node.node_name == 'integer')
    return true           if(node.node_name == 'true')
    return false          if(node.node_name == 'false')
    # etc.
end

doc = Nokogiri::XML('<xml>' + your_key_value_xml + '</xml>')
h   = doc.search('key').each_with_object({ }) { |n, h| h[n.text] = unpack_value(n.next_element) }

If you're XML already has the <xml> wrapper then you don't need to add them.

The doc.search call will give you an iterator with all the <key> elements. Then you iterate with each_with_object to build the hash. The text method gives you the node's content and next_element gives you the node that immediately follows the <key> you have in hand. You might have to tweak unpack_value a little to account for all the possible value types but that's pretty straight forward.

This approach will overwrite previous <key>s with new ones but it is pretty easy to change it produce an array of little single key hashes if you want to do something with the duplicates.

mu is too short
  • 426,620
  • 70
  • 833
  • 800