Building Web Applications with XML Databases

Thursday 12th November 2026

Part 1: Learning Objectives

XRX

What is XRX?

What is REST?

XQuery Processing Model (Web Platform)

Producing HTML from XQuery

Working for the Web from XQuery

Lab: Our First XQuery for the Web

Storing your first XML Collection into Elemental

Storing your first XML Collection into Elemental

In eXide:

  1. Click the Upload cloud icon
  2. Click the "Upload Files" button
  3. Choose the hindawi-small.zip file from your Computer
  4. Click the "x Done" button

Expanding the Zip File into a Collection

  1. Copy and Paste the following XQuery into eXide
  2. Click the Eval button to run the XQuery.

         let $collection-uri := xmldb:create-collection("/db", "hindawi-data")
         let $zip := util:binary-doc("/db/hindawi-small.zip")
         return
            compression:unzip($zip, compression:no-filter#3, (), function($path as xs:string, $dt as xs:string, $px as item()*) as xs:anyURI {
                  xs:anyURI($collection-uri || "/" || $path)
            }, ())
      

NOTE: Documents and Collections

Write a Subsequence Query


         <articles>
            <article year="2014" title="Understanding the Colour of Jake the Dog">
               <authors>
                  <author surname="The Human" given-names="Finn"/>
               </authors>
            </article>
            <article year="2014" title="Methods for the Hypnotisation of Princesses">
               <authors>
                  <author surname="Ice King" given-names="The"/>
               </authors>
            </article>
         </articles>
      

Hint: You might want to look into fn:subsequence

Subsequence Query - Solution


         <articles>
         {
            let $articles := subsequence(collection("/db/hindawi-data"), 1, 10)/article
            for $article in $articles
            let $authors := $article//contrib-group/contrib[ @contrib-type eq "author"]/name
            let $year := $article//pub-date[@pub-type eq "publication-year"]/year
            order by $year cast as xs:integer descending
            return
               <article year="{$year}" title="{$article//article-meta//article-title}">
                  <authors>
                    { $authors ! <author surname="{surname}" given-names="{given-names}"/> } 
                  </authors>
               </article> 
         } 
         </articles>
      

Stored Queries

You can store your XQuery into Elemental

Once the query is stored in the database you can do some cool stuff with the Web!

In eXide:

  1. Click the Save button
  2. Navigate into the /db/apps collection
  3. Click the Create Collection button, enter hindawi, and click Ok.
  4. Navigate into the new hindawi sub-collection
  5. Enter the name list.xq, click Save
Using eXide to store a XQuery into Elemental

Your query should now be present in the database at /db/apps/hindawi/list.xq

Executing your Query from the Web

HTML’ize your Query

Using eXide, modify your XQuery list.xq to produce HTML. You should:

Consider what you have learnt about the W3C W3C XSLT and XQuery Serialization 3.1 spec.

HTML’ize your Query - Solution


         declare namespace output="http://www.w3.org/2010/xslt-xquery-serialization";

         declare option output:method "html";
         declare option output:version "5";
         declare option output:media-type "text/html";

         <html>
            <h1>Journal Articles</h1>
            <table border="1">
               <tr>
                  <th>Year</th>
                  <th>Title</th>
                  <th>Authors</th>
               </tr>
               {
                  let $articles := subsequence(
                     for $article in collection("/db/hindawi-data")/article
                     order by
                         $article//pub-date[@pub-type eq "publication-year"]/year
                         cast as xs:integer descending
                     return $article 
                  , 1, 10)
                  return
                     for $article in $articles
                     let $authors := $article//contrib-group/contrib[@contrib-type eq "author"]/name
                     return
                        <tr>
                           <td>{$article//pub-date[ @pub-type eq "publication-year"]/year/text()}</td>
                           <td>{$article//article-meta//article-title/text()}</td>
                           <td>
                              <ul>
                                 { $authors ! <li>{string-join((surname, given-names), " ")}</li> }
                              </ul>
                           </td> 
                        </tr> 
               } 
            </table> 
         </html>
      

Part 1: What have we learned?

Part 2: Learning Objectives

URL Rewriting in Elemental

Meaningful/Consistent URLs

URLs that make perfect sense for a REST API or development aren't always well suited for end users!

Wouldn't the following URL:


      .../exist/rest/db/apps/hindawi/list.xq
    

be better if it could be accessed by the user as:


      www.hindawi.com/journal
    

?

URL Configuration Options

Elemental offers a few different ways of configuring user friendly URLs and URL interfaces:

URL Rewriting
Looks for an XQuery named controller.xq that controls how URLs are redirected
RestXQ
Allows you to create your own REST interface/URLs using annotations on function definitions.
Elemental supports RESTXQ out of the box.

In production systems, it is also quite common to install a HTTP Reverse Proxy in-front of Elemental to handle URI rewriting; see Production use - Proxying behind a Web Server.

URL Rewriting basics

controller.xq External Variables

When your controller.xq is executed, a number of variables describing the HTTP request URI are available for you to use.

For example with the URI path /exist/apps/hindawi/list.xq::

$exist:root The root of the current controller hierarchy. This may either point to the file system or to a collection in the database. Use this variable to locate resources relative to the root of the application. e.g.: xmldb:exist:/db/apps
$exist:resource The section of the URI after the last /, usually pointing to a resource or collection e.g.: list.xq
$exist:controller The part of the URI leading to the current controller script. e.g.: /hindawi
$exist:path The last part of the request URI after the section leading to the controller e.g.: /list.xq
$exist:prefix (Optional) Any prefix mapping of the current controller hierarchy e.g.: /apps

In addition to the provided variables, you can also call the Request Module to get data from the HTTP request

controller.xq Result

The controller.xq should return an XML document instructing Elemental how to process the request

Documentation of Elemental's Controller XML Format

Ignoring URLs

If you want to bypass the controller script entirely, you can return the ignore element instead of a dispatch:


      
      <ignore xmlns="http://exist.sourceforge.net/NS/exist"/>
      
    

This can be useful for requests for static resources (such as images, CSS, etc), or for where you are using the controller alongside another method for re-writing URLs.

The cache-control Option

The cache-control element may be used in either dispatch or ignore, and configures whether or not the current URL rewrite should be cached.

It has a single attribute cache, which must be set to either "yes" or "no".


      
      <dispatch xmlns="http://exist.sourceforge.net/NS/exist">
        <redirect url="..."/>
        <cache-control cache="yes"/>
      </dispatch>
      
    

Only the URL rewrite rule is cached, not the HTTP response.

controller.xq Example

To map the following URL path:


      /exist/apps/mycompany/department/digital/employee/fredsmith
    

to the XQuery:


      /exist/rest/db/apps/mycompany/employee-details.xq?dept=digital&name=fredsmith
    

The /db/apps/mycompany/controller.xq could look like:


      
      xquery version "3.1";

      declare variable $exist:path external;

      if (matches($exist:path, "^/department/[^/]+/employee/[^/]+$"))
      then
        let $department := replace($exist:path, "/department/([^/]+)/employee/[^/]+", "$1")
        let $employee := replace($exist:path, "/department/[^/]+/employee/([^/]+)", "$1")
        return

          <dispatch xmlns="http://exist.sourceforge.net/NS/exist">
            <forward url="employee-details.xq">
              <add-parameter name="dept" value="{$department}"/>
              <add-parameter name="name" value="{$employee}"/>
            </forward>
          </dispatch>
      else
        <ignore xmlns="http://exist.sourceforge.net/NS/exist"/>
      
    

Remember you have the full-power of XQuery available, and so you can do very complex URL rewriting if needed

Lab: Our First controller.xq

Your first controller.xq

Your first controller.xq - Solution

Your controller.xq should be stored at /db/apps/hindawi/controller.xq:


          
          xquery version "3.1";

declare variable $exist:path external;

if ($exist:path eq "/journal")
then
    <dispatch xmlns="http://exist.sourceforge.net/NS/exist">
      <forward url="list.xq"/>
    </dispatch>
else
    <ignore xmlns="http://exist.sourceforge.net/NS/exist"/>
          
        

Improving your first controller.xq

Improving your first controller.xq - Solution

Your controller.xq should be stored at /db/apps/hindawi/controller.xq:


          
            xquery version "3.1";

  declare variable $exist:path external;

  if ($exist:path = ("", "/"))
  then
    <h1>Welcome to hindawi</h1>
  else if ($exist:path eq "/journal")
  then
      <dispatch xmlns="http://exist.sourceforge.net/NS/exist">
        <forward url="list.xq"/>
      </dispatch>
  else
      <ignore xmlns="http://exist.sourceforge.net/NS/exist"/>
            
        

Elemental's Request and Response Modules

Elemental's Request Module

Elemental's Request Module - Functions

Commonly Used Functions

request:get-parameter Get the value of a HTTP Query or Form parameter
request:get-parameter-names Get the names of all available HTTP Query or Form parameters
request:get-data Get the content of a file sent (PUT/POST) to the server in the body of the request
request:get-uploaded-file Get the content of a file sent (POST) from an HTML form to the server
request:get-uploaded-file-name Get the filename of a file sent (POST) from an HTML form to the server

Request Module documentation

Request Module Examples

Given the URI:

http://localhost:8080/exist/rest/db/myquery.xq?abbrev=xmlss&year=2019

Get the value of the abbrev HTTP Query parameter:


      request:get-parameter("abbrev", ())
    

Get the name and value of all parameters:


      request:get-parameter-names() ! <param name="{.}" value="{request:get-parameter(., ())}"/>
    

Elemental's Response Module

Elemental's Response Module - Functions

Commonly Used Functions

response:set-status-code Set the value of the status code in the HTTP Response
response:redirect-to Redirect the client (e.g. web-browser) to a new location
response:stream-binary Stream binary data (e.g. a binary document from the database) to the HTTP response and commit the response.

Response Module documentation

Details of HTTP response codes

Response Module Examples

Lab: Client/Server Interaction with XQuery

Processing a Form

  • Use a Request Module function to get the value of the form field in your XQuery
  • A predicate or where clause can be used to restrict the results to a particular year

Processing a Form - Solution

The start of our list.xq query should now look like:


      <html>
        <h1>Journal Articles</h1>
        <form action="list.xq" method="post">
          <label for="year">Year:</label>
          <input name="year" id="year" value="{request:get-parameter('year',())}"/>
          <input type="submit"/>
        </form>
        <hr/>
        <table border="1"> ...</table>
      </html>
    

The For Clause from our previous inner FLWOR expression should now look like:


      for $article in collection("/db/hindawi-data")/article
      let $year := $article//pub-date[@pub-type eq "publication-year"]/year
      where $year eq request:get-parameter("year", ())
      order by $year
      cast as xs:integer descending
      return
        $article
    

Lab: Full Text Queries with XQuery

Full Text Queries

Full Text Queries in Elemental

Full Text Indexing


      <collection>
        <index>
          <lucene>
            <analyzer class="org.apache.lucene.analysis.standard.StandardAnalyzer"/>
            <text qname="article-title" boost="2.0"/>
            <text qname="p">
              <inline qname="sup"/>
              <inline qname="sub"/>
            </text>
          </lucene>
        </index>
      </collection>
    

Exercise - Full Text Indexing

You will need to use Elemental's ft:query function inside a predicate on the abstract of the article.

Elemental's Full Text Index documentation is here.

Exercise - Full Text Indexing - Solution

The end of our HTML form of our list.xq query:


      <form>
        ...
        <label for="keywords">Keywords:</label>
        <input name="keywords" id="keywords" value="{request:get-parameter('keywords', ())}"/>
        <input type="submit"/>
      </form>
    

Our initial FLWOR becomes:


      for $article in
        if(request:get-parameter("keywords", ()))
        then
          collection("/db/hindawi-data")/article[.//abstract[ft:query(p, request:get-parameter("keywords", ()))]]
        else
           collection("/db/hindawi-data")/article
      let $year := ...