Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Sinatra to serve XML documents?

Tags:

ruby

sinatra

I have some XML documents that I'd like to server from Sinatra. I did some searching but couldn't find anything specific. I did find the builder gem but I don't want to build the document from scratch.

I tried to do something like this

get '/'
  xml = '<?xml version=\"1.0\" encoding=\"UTF-8\"?> <name>My name</name> <age>90</age>'
  body xml
end

but that will add the HTML tags around it. It's probably something really basic I'm missing. Can you point me in the right direction please?

like image 720
Luis Avatar asked Nov 19 '10 17:11

Luis


People also ask

What is Sinatra framework?

Sinatra is a free and open source software web application library and domain-specific language written in Ruby. It is an alternative to other Ruby web application frameworks such as Ruby on Rails, Merb, Nitro, and Camping. It is dependent on the Rack web server interface. It is named after musician Frank Sinatra.


2 Answers

This is very simple with Sinatra:

get '/' do
  content_type 'text/xml'
  "<name>Luis</name><age>99</age>"
end

On get '/' the response will be the XML "<name>Luis</name><age>99</age>" with the correct content_type.

like image 160
19WAS85 Avatar answered Nov 07 '22 11:11

19WAS85


As answered below, in addition Wagner's answer of adding the content type, you must include only one XML root element http://www.w3schools.com/xml/xml_syntax.asp otherwise Sinatra will raise an exception.

So the complete answer is:

get '/'
  content_type 'text/xml'
  '<?xml version=\"1.0\" encoding=\"UTF-8\"?><root><name>My name</name> <zage>90</age></root>'
end
like image 24
naviram Avatar answered Nov 07 '22 10:11

naviram