← Back to Upcase

Create XML payload from database table

(Sidd Tewari) #1

How do you create XML payloads from database tables to be used for post and put/patch requests to an external API? What are the different ways one can create an XML payload from a database table?

(Derek Prior) #2

You are looking to take a ruby object and serialize it to XML. There are a number of ways to do this. Within rails, the simplest way is to use to_xml. I’d start there.

If you need to customize that XML a lot, something like builder might be more appropriate.

(Sidd Tewari) #3

Thanks! Right on the money. In the process of understanding and experimenting with builder - as of right now I’m using the: payload.instruct! # <?xml version="1.0" encoding="UTF-8"?> as a part of my method so that the instruction is included on top of the payload. However this link suggests that this “Instruct” method has been deprecated. Is there another or a better way to include the instruction in the payload? Is it still okay to use the instruct method?

Also this is how I’m currently using Builder to build the xml payload from my model / database table. Any suggestions/recommendations regarding improvements or alternative will be much appreciated!! Thanks again.

def self.upload_all_props()

    payload = ::Builder::XmlMarkup.new(:indent => 2)
    payload.instruct!                   # <?xml version="1.0" encoding="UTF-8"?>
    props = Prop.all
    # puts props.inspect
    props.each do |p|
      payload.prop do |prop|