问题
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>
but doing:
{"Car"=>[{"engine"=>"A", "wheels"=>"4"}, {"engine"=>"B", "wheels"=>"2"}]}.to_xml(:root => "Test")
returns:
<?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>
You see, I don't want the parent node "<Car type=\"array\">"
Any idea how to achieve this?
Thank you!
回答1:
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"
So More Concisely
{"Car"=>[{"engine"=>"A", "wheels"=>"4"}, {"engine"=>"B", "wheels"=>"2"}]}.values.pop.to_xml(:root => "Test", skip_types: true, children: "Car")
Will Return
<?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
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.
回答2:
How about utilizing the :skip_types => true option?
{"Car"=>[{"engine"=>"A", "wheels"=>"4"}, {"engine"=>"B", "wheels"=>"2"}]}.to_xml(:root => "Test", :skip_types => true)
来源:https://stackoverflow.com/questions/26282686/ruby-to-xml-with-repeating-same-nodes