Ruby to_xml,重复相同的节点

时间:2014-10-09 15:47:27

标签: ruby xml hash

我想生成类似的东西:

<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<Test>
  <Car>
    <engine>A</engine>
    <wheels>4</wheels>
  </Car>
  <Car>
    <engine>B</engine>
    <wheels>2</wheels>
  </Car>
</Test>

但正在做:

{"Car"=>[{"engine"=>"A", "wheels"=>"4"}, {"engine"=>"B", "wheels"=>"2"}]}.to_xml(:root => "Test")

返回:

<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<Test>
  <Car type=\"array\">
    <Car>
      <engine>A</engine>
      <wheels>4</wheels>
    </Car>
    <Car>
      <engine>B</engine>
      <wheels>2</wheels>
    </Car>
  </Car>
</Test>

你看,我不想要父节点"<Car type=\"array\">" 知道如何实现这个目标吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

对于这个简单的情况,您可以像{<1}}一样使用

Array#to_xml

如此简洁

values = {"Car"=>[{"engine"=>"A", "wheels"=>"4"}, {"engine"=>"B","wheels"=>"2"}]}.values.pop
#=> [{"engine"=>"A", "wheels"=>"4"}, {"engine"=>"B", "wheels"=>"2"}]
values.to_xml(:root => "Test", skip_types: true, children: "Car")
#=>"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Test>\n  <Car>\n    <engine>A</engine>\n    <wheels>4</wheels>\n  </Car>\n  <Car>\n    <engine>B</engine>\n    <wheels>2</wheels>\n  </Car>\n</Test>\n"

将返回

{"Car"=>[{"engine"=>"A", "wheels"=>"4"}, {"engine"=>"B", "wheels"=>"2"}]}.values.pop.to_xml(:root => "Test", skip_types: true, children: "Car")

<?xml version=\"1.0\" encoding=\"UTF-8\"?> <Test> <Car> <engine>A</engine> <wheels>4</wheels> </Car> <Car> <engine>B</engine> <wheels>2</wheels> </Car> </Test> 允许您传递Array#to_xmlroot个选项,以便命名children&#34;测试&#34;以及root&#34; Car&#34;按照要求。如果这只是一个例子并且情况更复杂,那么可能会有这种担忧,在这种情况下我会建议查看builder,它允许您对节点及其命名约定进行巨大的控制。

答案 1 :(得分:0)

How about utilizing the :skip_types => true option?

{"Car"=>[{"engine"=>"A", "wheels"=>"4"}, {"engine"=>"B", "wheels"=>"2"}]}.to_xml(:root => "Test", :skip_types => true)