XQuery/HelloWorld
< XQueryMotivation
You want to run a small program that tests to see if your XQuery execution environment is working.
XML Output
xquery version "1.0";
let $message := 'Hello World!'
return
<results>
<message>{$message}</message>
</results>
Expected Output
<results>
<message>Hello World!</message>
</results>
Discussion
The program creates a temporary variable called $message
and assigns it a string value. The output is an XML element containing a message element which contains the value of the variable.
Suggestions
Try omitting the curly braces from inside of the result message element. What do you get? Execute
What happens if you omit the results wrappers? Execute
Plain Text
You can get XQuery to return plain text using serialization options which define the serialization and the output media-type.
For example to output the message as text, specify the serialization as text and the media-type as text/plain.
xquery version "1.0";
declare option exist:serialize "method=text media-type=text/plain";
let $message := 'Hello World!'
return
$message
Expected Output
Depending on your browser set-up, this will launch a viewer for text documents and display
Hello World!
Execution Methods
If you are using the oXygen IDE this can be done by selecting the "transform" icon on the toolbar.
If you are running this program in the eXist databases you can upload a file called helloWorld.xq using the "Browse" function in the web administrator and then run the following in the browser:
http://localhost:8080/exist/rest/db/helloWorld.xq
There are three important items to note in this URL.
- This is the URL that you would use if you used the default eXist configuration
- Note that the word "rest" is in the URL before the "/db" indicating that you are using the REST interface (as opposed to the WebDAV, Atom or SOAP interface)
- Note that the port is "8080" (the default port for development web sites) and that the "context" of the server is "exist". Both of these can be easily changed by editing the $EXIST_HOME/tools/jetty/etc/conf.xml file and restarting your eXist server. The short-form on production sites might be:
http://localhost/rest/db/helloWorld.xq
With tools like URL rewriting you can also remove the "/rest" and the "/db" components of the URL.