Ruby XML到JSON转换器?

在Ruby中是否有一个将XML转换为JSON的库?

一个简单的技巧:

首先你需要gem install json ,然后在使用Rails的时候可以这样做:

 require 'json' Hash.from_xml('<variable type="product_code">5</variable>').to_json #=> "{\"variable\":\"5\"}" 

如果你不使用Rails,那么你可以gem install activesupport ,要求它,事情应该顺利。

例:

 require 'json' require 'net/http' s = Net::HTTP.get_response(URI.parse('http://stackoverflow.com/feeds/tag/ruby/')).body Hash.from_xml(s).to_json 

我会使用Crack ,一个简单的XML和JSONparsing器。

 require "rubygems" require "crack" require "json" myXML = Crack::XML.parse(File.read("my.xml")) myJSON = myXML.to_json 

如果你想保留所有的属性,我build议cobravsmongoose http://cobravsmongoose.rubyforge.org/使用badgerfish公约。;

 <alice sid="4"><bob sid="1">charlie</bob><bob sid="2">david</bob></alice> 

变为:

 {"alice":{"@sid":"4","bob":[{"$":"charlie","@sid":"1"},{"$":"david","@sid":"2"}]}} 

码:

 require 'rubygems' require 'cobravsmongoose' require 'json' xml = '<alice sid="4"><bob sid="1">charlie</bob><bob sid="2">david</bob></alice>' puts CobraVsMongoose.xml_to_hash(xml).to_json 

您可能会发现xml-to-json gem很有用。 它维护属性,处理指令和DTD语句。

安装

 gem install 'xml-to-json' 

用法

 require 'xml/to/json' xml = Nokogiri::XML '<root some-attr="hello">ayy lmao</root>' puts JSON.pretty_generate(xml.root) # Use `xml` instead of `xml.root` for information about the document, like DTD and stuff 

生产:

 { "type": "element", "name": "root", "attributes": [ { "type": "attribute", "name": "some-attr", "content": "hello", "line": 1 } ], "line": 1, "children": [ { "type": "text", "content": "ayy lmao", "line": 1 } ] } 

这是xml-to-hash的简单派生。

假设你正在使用libxml,你可以尝试一下这个变种(免责声明,这适用于我有限的用例,它可能需要调整是完全通用的)

 require 'xml/libxml' def jasonized jsonDoc = xml_to_hash(@doc.root) render :json => jsonDoc end def xml_to_hash(xml) hashed = Hash.new nodes = Array.new hashed[xml.name+"_attributes"] = xml.attributes.to_h if xml.attributes? xml.each_element { |n| h = xml_to_hash(n) if h.length > 0 then nodes << h else hashed[n.name] = n.content end } hashed[xml.name] = nodes if nodes.length > 0 return hashed end 

如果你正在寻找速度,我会推荐牛,因为它几乎是已经提到的最快的select。

我用一个XML文件运行了一些基准testing,这个testing结果来自omg.org/spec ,结果如下(秒):

 xml = File.read('path_to_file') Ox.parse(xml).to_json --> @real=44.400012533 Crack::XML.parse(xml).to_json --> @real=65.595127166 CobraVsMongoose.xml_to_hash(xml).to_json --> @real=112.003612029 Hash.from_xml(xml).to_json --> @real=442.474890548