xquery - 在支持多种输出格式的 exist-db 中编写一个 XQuery 脚本

标签 xquery exist-db

这是

的后续问题

Getting hold of tag content in XQuery 3.0 (exist-db)

假设这样的 xquery 脚本应该能够基于类似

的查询参数以 XML、JSON 或 HTML 的形式返回结果
http://host/exist/rest/db/myscript.xql?mode=xml|html|json

我知道如何从 XML -> JSON 更改序列化程序以及如何应用 使用 transform:transform() 的 XSLT 转换。

封装结果的 XML 生成然后根据请求参数将其转换为其中一种输出格式的最佳方法是什么?

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>
};

最佳答案

我建议看一下 eXist 中的 RESTXQ,因为它允许您根据内容协商或任何其他 HTTP 参数或 header 轻松控制结果格式。例如,使用内容协商来生成 XML、JSON 和 HTML 表现形式:

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>
};

关于xquery - 在支持多种输出格式的 exist-db 中编写一个 XQuery 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24525869/

相关文章:

xpath - 如何在xpath中获取元素类型?

operators - XQuery:将一个值与多个值进行比较,如 SQL "in"命令

exist-db - 在 Linux 中的文件系统上查找存储在 exist-db 中的 XML 文件

html - XSLT 无法使用 xs :output 添加 DOCTYPE

xml - 在 BaseX 中将 xml 从 XQuery 转换为 csv

XQuery:插入节点

xquery - 使用 eXist-db 中的范围索引提高查询性能

xquery:如何以相同的方式转换多个文件,但对一个文件进行特殊处理

xml - 如何使用 XPath 显示所有节点子节点、子节点以及更深层的节点

xml - 如何正确使用 QXmlQuery? (Qt XQuery/XPath)