在Ruby中将嵌套哈希转换为XML时,XML节点会被删除

时间:2013-11-21 04:23:18

标签: ruby xml hash

我使用以下代码将哈希转换为XML:

class Hash
    def to_xml
        map do |k,v|
            text = Hash === v ? v.to_xml : v
            "<%s>%s</%s>" % [k,text,k]
        end.join
    end

    def to_xml_with_namespace(ns)
        map do |k,v|
            text = Hash === v ? v.to_xml_with_namespace(ns) : v
            "<#{ns}:%s>%s</#{ns}:%s>" % [k,text,k]
        end.join
    end
end

一切正常,直到我有多个节点具有相同的值,例如:

{:users => { 
    :name_age_node => {:name => "Bob", :age => 50},
    :name_age_node => {:name => "Tom", :age => 45},
    :name_age_node => {:name => "Jess", :age => 22}
}

什么输出只是最后一个节点..其他节点由于某种原因被覆盖。没有重复节点同名的所有节点都可以,无论它们是否嵌套。

关于为什么会发生这种情况的任何想法?

1 个答案:

答案 0 :(得分:3)

你正在处理哈希。哈希仅支持特定键的单次出现:

foo = {:users => { 
    :name_age_node => {:name => "Bob", :age => 50},
    :name_age_node => {:name => "Tom", :age => 45},
    :name_age_node => {:name => "Jess", :age => 22}
  }
}
foo
# => {:users=>{:name_age_node=>{:name=>"Jess", :age=>22}}}

使用唯一键:

foo = {:users => { 
    :name_age_node1 => {:name => "Bob", :age => 50},
    :name_age_node2 => {:name => "Tom", :age => 45},
    :name_age_node3 => {:name => "Jess", :age => 22}
  }
}
foo
# => {:users=>
#      {:name_age_node1=>{:name=>"Bob", :age=>50},
#       :name_age_node2=>{:name=>"Tom", :age=>45},
#       :name_age_node3=>{:name=>"Jess", :age=>22}}}

或者您可以使用哈希数组来包含内部数据:

foo = {:users => [
    {:name => "Bob", :age => 50},
    {:name => "Tom", :age => 45},
    {:name => "Jess", :age => 22}
  ]
}
foo
# => {:users=>
#      [{:name=>"Bob", :age=>50},
#       {:name=>"Tom", :age=>45},
#       {:name=>"Jess", :age=>22}]}
#       :name_age_node3=>{:name=>"Jess", :age=>22}}}