问题
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