Blog
Handcrafted xml files with Ruby!
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 = Nokogiri::XML::Builder.new(:encoding => '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)
}
end
}
}
end
}
end
builder.to_xml
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: ERB.new(File.read("./documents.xml.erb"), 0, '>').result(binding) (binding allow you to access all call context variables).
Then, here is the XML template:
./documents.xml.erb
<Documents>
<% documents.each do |document| %>
<Document>
<DocumentTypeH><%= document.document_type %></DocumentTypeH>
<DocumentNb><%= document.document_nb %></DocumentNb>
<Lines>
<% document.lines.each_with_index do |line, index| %>
<Line>
<DocumentType><%= document.document_type %></DocumentType>
<DocumentNb><%= document.document_nb %></DocumentNb>
<LineNb><%= index + 1 %></LineNb>
</Line>
<% end %>
</Lines>
</Document>
<% end %>
</Documents>
Don’t hesitate to share your xml creation process !