1

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?

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

i wanted to use the hash for searching also. hence i cannot convert the keys to mykey. more over i dont want parse through the hash and change the keys.
what i actually did was, I passed the hash.values which is nothing but the array of hashes. then to_xml was able to generated the way i needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.