使用 ruby​​ 中的 xmlsimple 将哈希转换为 XML [英] converting hash to XML using xmlsimple in ruby

查看:24
本文介绍了使用 ruby​​ 中的 xmlsimple 将哈希转换为 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下格式的哈希

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

我想像下面那样将它转换成xml

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>

问题是,xmlsimple 没有这样做.而不是 put ,它正在创建 <1234> 标签.

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

我想摆脱这个……有什么帮助吗?甚至 ActiveSupport to_xml 也是如此.还有其他选择吗?

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

推荐答案

外层散列的 key 肯定是 1234234.xmlsimple 正在做正确的解析.您还没有在哈希中提到 MyKeysMyKey.您应该先将哈希转换为您需要的格式,然后再将其转换为 xml.

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}

在这个哈希上使用 xmlsimple.

Use xmlsimple on this hash.

这篇关于使用 ruby​​ 中的 xmlsimple 将哈希转换为 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆