Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Play! Framework to serve a XML response

Somehow I can't figure out how to get Play! to serve an XML response. And I don't understand the documentation either (which you can find here).

My goal is to create a sitemap, so the response should be a Content-Type: application/xml;

How would you alter the following controller to serve that Content-Type?

public static Result sitemap() {
    return ok("<message \"status\"=\"OK\">Hello Paul</message>");
}
like image 669
Crayl Avatar asked Dec 02 '13 06:12

Crayl


People also ask

What is an XML response?

XML request and response support consists of two main functions: The XML parsing function parses an inbound XML request message and maps XML elements to a fixed format COMMAREA. See XML message formats for a sample of a request message in XML format.

How do you set content type explicitly on play?

Changing the default Content-Type Will automatically set the Content-Type header to text/plain , while: JsonNode json = Json. toJson(object); Result jsonResult = ok(json); will set the Content-Type header to application/json .


1 Answers

Play will set Content-type header properly if you will deliver it to ok() method in right way. For an example if you are returning the String (as you showed in question) it considers that's text/plain. You have at least 2 ways, the fastest (but ugly) is forcing content type, Jürgen suggest setting it to response, but de facto Play has a shortcut:

public static Result sitemap() {
    return ok("<message status=\"OK\">Hello Paul</message>").as("text/xml");
}

On the other hand probably using XML template is better and cleaner option than building it with glued strings... Just create the XML file:

/app/views/sitemap.scala.xml:

<message status="OK">John Doe</message>

So you can use it as easy as:

public static Result index() {
    return ok(views.xml.sitemap.render());
}

Of course this file is common Play's template, so you can pass data to it and process inside (ie. iterate list of items, etc)

like image 91
biesior Avatar answered Oct 10 '22 03:10

biesior