Reputation:
This is a followup question to
Getting hold of tag content in XQuery 3.0 (exist-db)
Assume that such an xquery script should be able to return the result as XML, JSON or HTML base on a query parameter like
http://host/exist/rest/db/myscript.xql?mode=xml|html|json
I know how to change the serializer from XML -> JSON and how to apply an XSLT transformation using transform:transform().
What is the best approach for encapsulating the XML generation for result and then transforming it based on the request parameter into one of output formats?
xquery version "3.0";
module namespace services = "http://my/services";
import module namespace transform = "http://exist-db.org/xquery/transform";
declare namespace rest = "http://exquery.org/ns/restxq";
declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";
declare
%rest:GET
%rest:path("/data.html")
%output:media-type("text/html")
%output:method("html5")
function services:home() {
transform:transform(services:example1(), doc("/db/my-xml-to-html.xslt"), ())
};
declare
%rest:GET
%rest:path("/data.json")
%rest:produces("application/json")
%output:method("json")
function services:home-json() {
services:example1()
};
declare
%rest:GET
%rest:path("/data.xml")
%rest:produces("application/xml")
function services:home-xml() {
services:example1()
};
declare
%private
function services:example1() {
<some>
<data>hello world</data>
</some>
};
Upvotes: 3
Views: 838
Reputation: 3517
I would suggest taking a look at RESTXQ in eXist, as this allows you to easily control the result format based on content negotiation or any other HTTP parameters or headers. For example using content negotiation to produce XML, JSON and HTML manifestations:
xquery version "3.0";
module namespace services = "http://my/services";
import module namespace transform = "http://exist-db.org/xquery/transform";
declare namespace rest = "http://exquery.org/ns/restxq";
declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";
declare
%rest:GET
%rest:path("/data")
%rest:produces("text/html")
%output:method("html5")
function services:home() {
transform:transform(services:example1(), doc("/db/my-xml-to-html.xslt"), ())
};
declare
%rest:GET
%rest:path("/data")
%rest:produces("application/json")
%output:method("json")
function services:home-json() {
services:example1()
};
declare
%rest:GET
%rest:path("/data")
%rest:produces("application/xml")
function services:home-xml() {
services:example1()
};
declare
%private
function services:example1() {
<some>
<data>here</data>
</some>
};
Upvotes: 4