book a call

estimate project

The belighted Blog

Handcrafted xml files with Ruby!

by Stéphane A., on 11 February 2014

On a daily basis we build API in order to feed all our projects ( such as our hot new NomadSuite ) and in our way to face such difficulties, we rely on the good old JSON format.

But sometimes, the industry standards required us to use the well known and spread XML format.

Here are two gems that can allow you to easily craft your own xml file, an old one called Builder and another, a bit more complete, called Nokogiri.

We’ll take this last one to show you, what are these capabilities:

First of all, add gem "nokogiri" to your gemfile and run the bundle install command.

Then, start to write your script !

builder = => 'UTF-8') do |xml| 
 xml.Documents { 
 documents.each do |document| 
 xml.Document { 
 xml.DocumentTypeH document.document_type 
 xml.DocumentNb document.document_nb 
 xml.Lines { 
 document.lines.each_with_index do |line, index| 
 xml.Line { 
 xml.DocumentType document.document_type 
 xml.DocumentNb document.document_nb 
 xml.LineNb (index + 1) 

Another option that we consider sometimes, is also to use the famous erb template language to generate the desired XML output.

For instance, have a look at this small piece of code:

You basicaly need nothing more than ruby (as erb is a ruby core library).

Just instanciate the class:"./documents.xml.erb"), 0, '>').result(binding) (binding allow you to access all call context variables).

Then, here is the XML template:


 <% documents.each do |document| %> 
 <DocumentTypeH><%= document.document_type %></DocumentTypeH> 
 <DocumentNb><%= document.document_nb %></DocumentNb> 
 <% document.lines.each_with_index do |line, index| %> 
 <DocumentType><%= document.document_type %></DocumentType> 
 <DocumentNb><%= document.document_nb %></DocumentNb> 
 <LineNb><%= index + 1 %></LineNb> 
 <% end %> 
 <% end %> 

Don’t hesitate to share your xml creation process !

Topics:      Under the hood

What is SaaS?

Everything You Need to Know About Moving to a SaaS Model.

Get the guide now >

Subscribe to Updates