converting hash to XML using xmlsimple in ruby

心不动则不痛 提交于 2019-12-24 09:37:04

问题


I have a hash of the following format

{
 '1234' => {"key1"=>1234,"key2"=>"sdfsdf","key3"=>"sdfsdfs"},
 '234' => {"key1"=>234,"key2"=>"sdfsdf","key3"=>"sdfsdfs"}
}

I want to convert it to xml like below

<?xml version="1.0" encoding="UTF-8"?>
<MyKeys>
  <MyKey>
    <Key1>1234/Key1>
    <Key2>sdfsdf</Key2>
    <Key3>sdfsdfs</Key3>
  </MyKey>
  <MyKey>
    <Key1>234/Key1>
    <Key2>sdfsdf</Key2>
    <Key3>sdfsdfs</Key3>
  </MyKey>
</MyKeys>

the issue is, xmlsimple is not doing that. instead of putting , it is creating <1234> tag.

I want to get rid of this.... any help? even ActiveSupport to_xml does the same. any other options available?


回答1:


The key for the outer hash is definitely 1234 and 234. xmlsimple is doing the correct parsing. You havent mentioned of MyKeys or MyKey in your hash. You should convert the hash to your required format before converting it to xml.

hash = {
 '1234' => {"key1"=>1234,"key2"=>"sdfsdf","key3"=>"sdfsdfs"},
 '234' => {"key1"=>234,"key2"=>"sdfsdf","key3"=>"sdfsdfs"}
}
converted_hash = Hash[hash.map{|k, v| ["MyKey", v]}]
result_hash = {"MyKeys" => converted_hash}

Use xmlsimple on this hash.



来源:https://stackoverflow.com/questions/5193587/converting-hash-to-xml-using-xmlsimple-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!