15

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?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Luis
  • 171
  • 1
  • 5

2 Answers2

38

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.

19WAS85
  • 2,853
  • 1
  • 20
  • 19
  • I knew it was something simple... Should've thought of that! – Luis Nov 19 '10 at 18:32
  • 1
    I wish I could accept answers on behalf of askers after a few years. – D. Patrick Apr 23 '14 at 19:18
  • This answer is no completely right and have an exception on the Sinatra level. XML should have only one root element: http://www.w3schools.com/xml/xml_syntax.asp – naviram Jul 01 '16 at 14:40
2

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
naviram
  • 1,445
  • 1
  • 15
  • 26