Code:
require 'builder'
my_array = [["sam", "string 1"], ["sam", "string 2"], ["joe", "string 1"]]
my_hash = my_array.inject(Hash.new { [] }) { |g,p| g[p[0]] <<= p[1]; g }
xml = Builder::XmlMarkup.new(:target => (my_output = ''), :indent => 1)
xml.people do
my_hash.each do |name, dialogs|
xml.person :name => name do
dialogs.each do |dialog| xml.dialog dialog end
end
end
end
print my_output
Outputs this;
Code:
<people>
<person name="joe">
<dialog>string 1</dialog>
</person>
<person name="sam">
<dialog>string 1</dialog>
<dialog>string 2</dialog>
</person>
</people>
Don't know if I really understood the problem, but at least it looks like what you wanted to end up with, so I hope it helped somewhat.
I suppose if you wanted to add a new node you could just:
my_array << ["sam", "some more"]
and generate the xml again.
Bookmarks