简体   繁体   English

如何保持XML Array中的顺序到Hash转换?

[英]How to retain order in XML Array to Hash conversion?

I'm trying to parse XML in Ruby using Nori, which internally uses Nokogiri. 我正在尝试使用Nori解析Ruby中的XML,Nori内部使用Nokogiri。 The XML has some tags repeated and the library parses repeated tags as Arrays and non-repeated tags as normal elements (Hash) XML重复了一些标记,并且库将重复的标记解析为数组,将非重复的标记解析为普通元素(哈希)

<nodes>
  <foo>
    <name>a</name>
  </foo>
  <bar>
    <name>b</name>
  </bar>
  <baz>
    <name>c</name>
  </baz>
  <foo>
    <name>d</name>
  </foo>
  <bar>
    <name>e</name>
  </bar>
</nodes>

is parsed as 被解析为

{nodes: {
  foo: [{name: "a"}, {name: "d"}],
  bar: [{name: "b"}, {name: "e"}],
  baz: {name: "c"}
}}

How do i retain the order of elements in the resulting hash like the output below? 如何在结果哈希中保留元素的顺序,如下面的输出?

{nodes: [
      {foo: {name: "a"}}, 
      {bar: {name: "b"}},
      {baz: {name: "c"}},
      {foo: {name: "d"}},
      {bar: {name: "e"}},
    ]}

(This may be a library specific question. But the intention is to know if anyone has faced a similar issue and how to parse it correctly) (这可能是一个特定于图书馆的问题。但目的是要知道是否有人遇到过类似问题以及如何正确解析它)

Nori can't do this on its own. Nori不能单独做到这一点。 What you can do is tune the Nori output like this: 您可以做的是调整Nori输出,如下所示:

input = {nodes: {
  foo: [{name: "a"}, {name: "d"}],
  bar: [{name: "b"}, {name: "e"}],
  baz: {name: "c"}
}}

def unfurl(hash)
  out=[]
  hash.each_pair{|k,v|
    case v
    when Array
      v.each{|item|
        out << {k => item}
      }
    else
      out << {k => v}
    end
  }
  return out
end

output = {:nodes => unfurl(input[:nodes])}

puts output.inspect

This prints the output that the original question requested which is different than the XML order: 这将打印原始问题所请求的输出,该输出与XML顺序不同:

{nodes: [
  {foo: {name: "a"}}, 
  {foo: {name: "d"}},
  {bar: {name: "b"}},
  {bar: {name: "e"}},
  {baz: {name: "c"}},
]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM