tybro0103
tybro0103

Reputation: 49693

Ruby Hash & Array to xml

I'm using ActiveSupport's to_xml to generate some xml from a hash.

I have need for the this ruby:

:Shipment => {
  :Packages => [
    {:weight => '5', :type => 'box'},
    {:weight => '3', :type => 'tube'}
  ]
}

To generate this xml:

<Shipment>
  <Package>
    <weight>5</weight>
    <type>box</type>
  </Package>
  <Package>
    <weight>3</weight>
    <type>tube</type>
  </Package>
</Shipment>

But instead, it wraps the array in another set of xml tags like this:

<Shipment>
  <Packages>
    <Package>
      <weight>5</weight>
      <type>box</type>
    </Package>
    <Package>
      <weight>3</weight>
      <type>tube</type>
    </Package>
  </Packages>
</Shipment>

Please don't tell me I need to change my xml structure... It's how UPS says to do it :(

Anybody know a work-around?

Upvotes: 1

Views: 2608

Answers (1)

ghoppe
ghoppe

Reputation: 21784

Checking out builder is the way to go. Your xml.builder will look something like:

xml.shipment do
    @packages.each do |package|
        xml.package do
            xml.weight package.weight
            xml.type package.type
        end
    end
end

Upvotes: 4

Related Questions