Ruby XML 到 JSON 转换器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1530324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:19:52  来源:igfitidea点击:

Ruby XML to JSON Converter?

xmlrubyjsonconverter

提问by Lance Pollard

Is there a library to convert XML to JSON in Ruby?

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

回答by khelll

A simple trick:

一个简单的技巧:

First you need to gem install json, then when using Rails you can do:

首先你需要gem install json,然后在使用 Rails 时你可以:

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

If you are not using Rails, then you can gem install activesupport, require it and things should work smoothly.

如果您不使用 Rails,那么您可以gem install activesupport要求它,并且事情应该会顺利进行。

Example:

例子:

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

回答by neilfws

I'd use Crack, a simple XML and JSON parser.

我会使用Crack,一个简单的 XML 和 JSON 解析器。

require "rubygems"
require "crack"
require "json"

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

回答by Corban Brook

If you wish to keep all attributes I recommend cobravsmongoose http://cobravsmongoose.rubyforge.org/which uses the badgerfish convention.

如果您希望保留所有属性,我建议使用 cobravsmongoose http://cobravsmongoose.rubyforge.org/它使用獾约定。

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

becomes:

变成:

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

code:

代码:

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

回答by Maarten

You may find the xml-to-jsongemuseful. It maintains attributes, processing instruction and DTD statements.

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

Install

安装

gem install 'xml-to-json'

Usage

用法

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

Produces:

产生:

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

It's a simple derivative of xml-to-hash.

它是 的简单导数xml-to-hash

回答by Dan F.

If you're looking for speed I would recommend Oxsince it's pretty much the fastest option from the ones already mentioned.

如果您正在寻找速度,我会推荐Ox,因为它几乎是已经提到的最快的选择。

I ran some benchmarks using an XML file that has 1.1 MB from omg.org/specand these are the results(in seconds):

我使用来自omg.org/spec 的1.1 MB 的 XML 文件运行了一些基准测试 ,这些是结果(以秒为单位):

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

回答by erwin

Assuming you're using libxml, you can try a variation of this (disclaimer, this works for my limited use case, it may need tweaking to be fully generic)

假设您使用的是 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

回答by Alex V

Simple, without dependencies.

简单,无依赖。

Hash.from_xml(xml_string).to_json