Ruby to_xml具有重复的相同节点 [英] Ruby to_xml with repeating same nodes

查看:53
本文介绍了Ruby to_xml具有重复的相同节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成类似这样的东西:

I would like to generate something like:

<?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 \>" 知道如何实现吗?

You see, I don't want the parent node "<Car type=\"array\">" Any idea how to achieve this?

谢谢!

推荐答案

在这种简单情况下,您可以像这样使用 Array#to_xml

For this simple case you can use Array#to_xml like so

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_xml 允许您传入 root children 选项,以便您可以命名 root 测试"和 children 汽车"(按要求).如果这仅是示例,并且情况更复杂,则可能存在与这种情况有关的问题,在这种情况下,我建议您查看构建器,它使您可以极大地控制节点及其命名约定.

Array#to_xml allows you to pass in root and children options so you can name the root "Test" and the children "Car" as requested. If this was just an example and the case is more complex then there could be concerns with this in which case I would recommend looking at builder which allows you immense control over nodes and their naming conventions.

这篇关于Ruby to_xml具有重复的相同节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆