1

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?

1
  • I was just checking out Builder...looks pretty cool. Any recommendations to other ruby xml tools would be great. I already checked out xml-simple...it seems a little limited. REXML seems like it may be complicated to just change a hash to xml. Commented Feb 1, 2010 at 5:25

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.