【问题标题】:convert XML to ruby hash with attributes将 XML 转换为具有属性的 ruby​​ 哈希
【发布时间】:2015-04-03 19:14:27
【问题描述】:

目标:

将 XML 转换为 ruby​​ Hash ,包含所有节点和属性值

我尝试了什么:

xml  = 
  '<test id="appears">
    <comment id="doesnt appear">
      it worked
    </comment>
    <comment>
     see!
    </comment>
    <comment />
  </test>'

hash = Hash.from_xml(xml)

现在我得到了这个哈希

#=>{"test"=>{"id"=>"appears", "comment"=>["it worked", "see!", nil]}}

注意第一个评论元素上的 id 属性没有出现。

如何解决这个问题?

【问题讨论】:

    标签: ruby-on-rails ruby xml


    【解决方案1】:

    主动支持 XMLConverter 类的问题 请将以下代码添加到您的任何初始化程序文件中。

    module ActiveSupport
        class XMLConverter
            private
                def become_content?(value)
                    value['type'] == 'file' || (value['__content__'] && (value.keys.size == 1 && value['__content__'].present?))
                end
        end
    end
    

    它会给你如下输出。

    Ex 输入 XML

    xml = '<album>
       <song-name type="published">Do Re Mi</song-name>
    </album>'
    
    Hash.from_xml(xml)
    

    输出将是

    {"album"=>{"song_name"=>{"type"=>"published", "__content__"=>"Do Re Mi"}}}
    

    【讨论】:

      【解决方案2】:

      我发现这里的解决方案是 gem

      gem 'cobravsmongoose', '~> 0.0.2'
      

      试试这个,

        hash =CobraVsMongoose.xml_to_hash(xml)
      

      结果如下:

      {"test"=>{"@id"=>"appears", "comment"=>[{"@id"=>"doesnt appear", "$"=>"it worked"}, {"$"=>"see!"}, {}]}}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-08-26
        • 2010-12-16
        • 1970-01-01
        • 1970-01-01
        • 2013-07-08
        • 2021-07-13
        • 1970-01-01
        相关资源
        最近更新 更多