为什么使用 Hash#from_xml 将 Nokogiri XML 转换为 JSON 会删除内容?

Why does converting Nokogiri XML to JSON with Hash#from_xml remove content?

在将 Nokogiri 对象转换为 XML,然后再转换为 JSON 时,大部分内容都消失了。

获取数据并转换的代码:

def get_data
  doc = Nokogiri::HTML(open("<url>", "User-Agent" => "Ruby/#{RUBY_VERSION}"))

  # Get interesting block of HTML
  blurb = doc.css('.entry')

  # Convert Nokogiri object to XML
  xmlBlurb = blurb.to_xml

  # Convert to JSON
  jsonBlurb = Hash.from_xml(xmlBlurb).to_json

  return jsonBlurb 
end

xmlBlurbjsonBlurb 之间,我从 10 多行 XML 到单个 JSON 对象 { attr: content } 1 个属性。

我知道 SO 上有几个关于将 XML 转换为 JSON 的问题,但我阅读的 none 解决了这个特定问题。

有谁知道什么会导致数据丢失?

Hash#from_xml 是 Rails 对标准库 Hash class 的补充。该方法被记录为在从 XML 到 Hash.

的转换过程中在各种条件下丢失属性的麻烦

"convert XML to ruby hash with attributes" 提供了一些建议。

来源: