XQuery Examples Collection 
Current Status 
We are in the process of testing many of these examples using the eXist 2.0 release. Please let us know if you find any problems. We are looking for volunteers to help us create XQuery 3.0 examples.
New and Revised Articles 
About this Project 
This is a collaborative project and we encourage everyone who is using XQuery to contribute their XQuery examples. All example programs must conform to the creative-commons-2.5 share-alike with attribution license agreement .
Execution of examples use an eXist demo server.
- Instructors: please sign our Guest Registry if you are using this book for learning or teaching XQuery
- Contributors: please see our Naming Conventions to ensure your examples are consistent with the textbook
- Learners: If you are looking for an example of a specific XQuery language construct, technique or problem but can't find an example, please add a suggestion to the Examples Wanted section.
- Background - A brief history and motivation for the XQuery standard.
- Benefits - Why use XQuery?
- Installing and Testing - How to install an XQuery server on your .
- Naming Conventions - Naming standards used throughout this book.
Example Scripts 
Beginning Examples 
Examples that do not assume knowledge of functions and modules.
- HelloWorld - A simple test to see if XQuery is installed correctly.
- Loading data - A tour of several different ways to load data into a native XML database
- FLWOR Expression - A basic example of how XQuery FLWOR statements work.
- Sequences - Working with sequences is central to XQuery.
- Parsing CSV - Using FLWOR on sequences to parse CSV text.
- XPath examples - Sample XPath samples for people new to XML and XPath
- Regular Expressions - Regular expressions make it easy to parse text.
- Searching multiple collections - How to search multiple collections in a database.
- Getting URL Parameters - How to get parameters from the URL.
- Getting POST Data - How to get XML data posted to an XQuery.
- Checking for Required Parameters - How to check for a required parameter using if/then/else.
- Displaying Lists - How to take a list of values in an XML structure and return a comma separated list.
- Extracting data from XHTML files - How to use the doc() function to get data from XHTML pages.
- Displaying data in HTML Tables - How to display XML data in an HTML table.
- Limiting Result Sets - How to limit the number of records returned in an XQuery.
- Filtering Words - How to test to see if a word is on a list.
- Saving and Updating Data - How to have a single XQuery that saves new records or updates existing records.
- Quantified Expressions - Testing all the items in a sequence.
- Dates and Time - Sample expressions that work with date and time values
- Chaining Web Forms - Passing data from one web page to another using URL parameters, sessions or cookies
Intermediate Examples 
Assumes knowledge of functions and modules.
- Using XQuery Functions - How to read XQuery function documents and user XQuery functions
- Creating XQuery Functions - How to create your own local XQuery functions
- Returning the Longest String - A function to find the longest string from a list of strings
- Net Working Days - How to calculate the number of working days between two dates
- Tag Cloud - Counting and viewing the number of keywords
- String Analysis - Regular expression string analysis
- Manipulating URIs - How to get and manage URIs
- Parsing Query Strings - Parsing query strings using alternate delimiters.
- Splitting Files - Splitting a large XML files into many smaller files.
- Filling Portlets - How to fill regions of a web page with XQuery
- Filtering Nodes - How to use the identity transform to filter out nodes and add nodes
- Limiting Child Trees - You have a tree of information and you want to "prune" only at a specific level
- Higher Order Functions - Passing functions as arguments to functions
- Timing Fibonacci algorithms - A couple of Fibonacci algorithms and timing display
- Using Intermediate Documents - Analysis of a MusicXML file
- Formatting Numbers - using picture formats to format numbers
- Uploading Files - how to upload files using HTML forms
- TEI Concordance - How to build a TEI-based concordance
- Introduction to XML Search - An overview of XML search terminology
- Basic Search - A simple search page
- Searching,Paging and Sorting - Searching and Viewing search results
- Keyword Search - full text search with Google-style results
- Employee Search - an Ajax example
- Incremental Search of the Chemical Elements - with Ajax
- Lucene Search - using eXist's Lucene-based fulltext search
- Advanced Search - creating complex searches using multiple search fields
- Open Search - creating an OpenSearch file to describe your search page
- Auto-generation of Index Config Files - scripts to automatically generate the index configuration file
- Adder - Creating a web service that adds two numbers.
- Simple XForms Examples
- Navigating Collections - an example of an AJAX browser
- Sending E-mail - How to send an e-mail message from within an XQuery
Creating Custom Views 
These examples use reflection on the structure of an XML document using name() to implement generic functions for XML transformations.
- HTML Table View - A generic HTML table representation
- Tree View - A generic HTML tree representation
- Grouping Items - how to group items in a report
Transforming Complex XML Documents 
XQuery has many features that allow you to transform XML and create full document-style transformation libraries. Unlike traditional "database" documents, complex XML documents have "complex content" that includes in-line elements in unpredictable order. This section provides a foundation for these transformations based on using the XQuery typeswitch functions. Typeswitch function transformations replace XSLT transforms but can also access indexes for very fast transforms of large collections.
- Transformation Styles overview of the three styles of transformation
- Typeswitch Transformations Using the typeswitch function for document-style transforms.
- Transformation idioms Handling transformation tasks
- Generating Skeleton Typeswitch Transformation Modules Using XQuery to generate a skeleton module for typeswitch-based document transformation
- Web XML Viewer Using the typeswitch function to transform an XML document to HTML
Paginated Reports 
Unlike HTML pages, paginated reports use the concept of text flows between pages. These examples show you how to convert raw XML into high-quality PDF files suitable for printing. The examples use a markup standard called XSL-FO for "Formatted Objects"
- Installing_the_XSL-FO_module - update your 1.4 configuration to get the current software from the Apache web site
- Generating PDF from XSL-FO files - Converting XML-FO to PDF files
- XSL-FO Tables - Generating XSL-FO tables from XML files
- Converting HTML tables to XSL-FO tables - use a XQuery typeswitch transform to convert HTML tables to XSL-FO tables
- XSL-FO Images - Embedding images in generated (PDF) files
Content Publishing 
- Publishing Overview - How to transfer a document from an internal intranet server to a public web site
- Publishing to Subversion - How to transfer a document from an internal intranet to a public SVN server using SSL and digest authentication
XML Document Comparison and Merging 
- Compare two XML files - using the eXist compare() function to test to see if two XML files are exactly the same
- XML Differences - displaying the difference between two XML files
- Compare with XQuery - Using XQuery to Compare Lists
- Time Comparison with XQuery - Using XQuery to Compare Dated Items
- Synchronizing Remote Collections - Using lastModified time stamps to see what items have changed
- Finding Duplicate Documents - Using a hash function to find duplicate documents
Time Based Queries 
- Time Based Queries - using dates and times to limit search results
- Timing a Query - profiling how long a query takes
XML document kinds 
TEI documents 
Text Encoding Initiative.
- TEI Concordance - How to build a TEI-based concordance
- TEI Document Timeline - Using Simile Timeline to visualize a TEI document
DocBook Documents 
Office Open XML 
XML Schemas 
Processing Special Characters 
- Special Characters - dealing with newlines and other special characters.
XQuery and other languages 
Language Comparisons 
- XQuery SQL Module - Calling SQL from within your XQuery
- XQuery from SQL - Using XQuery to access a classic Relational database - Employee/Department/Salary
- List OWL Classes - A simple XQuery script that will display all the OWL classes in an OWL file
Language combination 
- Navigating Collections - basic AJAX
- Employee Search - basic AJAX
- Incremental Search of the Chemical Elements - AJAX
- DOJO data - basic JSON
XHTML + Voice 
- XQuery and XSLT Executing an XSLT transform from within XQuery
Data Mashups 
- Basic Authentication - Logging in to a remote web server using HTTP Basic Authentication
- Digest Authentication - Logging in to a remote web server using HTTP Digest Authentication
- OAuth - A standard for protecting a set of user-owed data within a web service
Wikipedia interaction 
Wikibook applications 
- Graph Visualization
- Graphing from RDF
- Dataflow diagrams
- Sequence Diagrams
- Example Sequencer - Step-by-step tutorial
Google Charts 
Although the Google Charts functions only work when you are connected to the Internet, these examples show that XQuery is an ideal tool for converting XML data into charts.
- Google Charts Using XML and XQuery to generate Google Charts using REST
- Google Chart Sparkline - A demonstration of how to create a chart using the Google Charts API
- Google Chart Bullet Bar - A demonstration of how to a dashboard bullet bar using the Google Charts API
- Histogram of File Sizes - An XQuery report that generates a histogram of file sizes
There are also sample XForms that can be used to create front-ends in the XForms Tutorial and Cookbook
Digital Dashboards 
Digital dashboards are single screens that compress a great deal of information into a single web page. This section will leverage many of the Google Charts examples from the prior section.
- Dashboard Architecture - How to design dashboards that have fast response times
Page Scraping 
Page scraping is the process of extracting well-formed XML data from any HTML web page. When creating mashup applications this is also known as the harvesting process.
- Overview of Page Scraping Techniques
- Page scraping and Yahoo Weather
- UK shipping forecast
- BBC Weather Forecast
- Page scraping and Mashup
- Simple RSS reader
- Multiple page scraping and Voting behaviour
- Link gathering
- REST interface definition
- Caching and indexes
- Google Geocoding
- /String Analysis#Location_Mapping/ Mapping Car Registrations
- Flickr GoogleEarth
- Nationalgrid and Google Maps
- SMS tracker
- Creating a Timeline - Creating a simple timeline view of events
- Timelines of Resource - Using creation and modification dates to create timelines
- TEI Document Timeline - Creating a timeline of all dates within a single TEI document
The Semantic Web 
- DBpedia with SPARQL - Football teams
- DBpedia with SPARQL and Simile Timeline - Album Chronology Creating a timeline of album releases using data from Wikipedia
- DBpedia with SPARQL - Stadium locations
- The Emp-Dept case study
- Graphing Triples
- SPARQLing Country Calling Codes
- Southampton Pubs
- Alphabet Poster
- Latent Semantic Indexing Finding the semantic distance between documents
Development Tools 
- Sitemap for Content Management System XQuery functions can easily perform many common web site content management functions
- Uptime monitor use XQuery to monitor a remote web service
- XQuery IDE - XQuery Integrated development environment
- Image Library - using an XQuery to preview your images
- XML Schema to Instance - XQuery function to generate a sample XML instance from an XML Schema file (.xsd)
- Lorum Ipsum text - generating sample text for inserting into test page layouts
- XQuery and XML Schema - Generating an XML instance document
- Generating XQDocs - Automating the generation of XQuery documentation for Modules and Functions
- XqUSEme - Firefox extension to allow XQueries including against the loaded document (even against originally non-XML (poorly formed) HTML).
- Validating a document - Validate a document with an XML Schema
- Validation using a Catalog - Using a Catalog file to validate documents
- Validating a hierarchy -
Path Analysis 
- All Paths - A report of all paths in a document or collection
- All Leaf Paths - A report of all leaf paths in a document or collection
- Login and Logout - How to log users in and log them out
- URL Driven Authorization How to use URL rewriting to check for valid users
- Digital Signatures - How to use a custom module to use the XML Digital Signature standards
- Changing Permissions on Collections and Resources - how to change permissions on collections and resources
Unit Testing Tools 
- XUnit Testing - what is XUnit testing and how to set them up
- XUnit Annotations - how to add annotations to your XQuery functions to drive your XUnit tests
Case Studies 
- Project Euler
- Topological Sort
- Pachube feed
- World Temperature records - conversion of text data formats to XML, indexing and data presentation
- UWE StudentsOnline
eXist db specific Functions and Configuration 
Installing modules 
Setting HTTP Headers 
ftp client 
This module allows you to interact with a remote FTP server on a remote system. It includes functions for listing, getting and putting files.
EXPath File Transfer XQuery Extension Module 
This module does both FTP, SFTP (using the SSH protocol) using a standardized and consistent format.
- Getting URL Parameters
- Getting POST Data
- Checking for Required Parameters
- Manipulating URIs
- Parsing Query Strings
- Adder simple client-server interaction
- Sequences Module - three additional functions (map, fold and filter)
- Basic Session Management - the basics of session management including getting a setting session variables
- Subversion - how to update a subversion repository from within XQuery using the subversion client
- Registered Modules : util:registered-modules()
- Registered Functions : util:registered-functions()
- Dynamic Module Loading : util:import-module(), util:eval()
- Higher Order Functions : util:function(), util:call()
- Timing Fibonacci algorithms : util:function(), util:call(), util:system-time()
- XMP data : util:binary-doc(), util:binary-to-string(), util:parse()
- Basic Authentication : util:string-to-binary(), httpclient:get()
XSL-FO (Formatted Objects) is a way of converting XML into PDF. Function Reference
- Installing the XSL-FO module - setting up your XSL-Module within eXist
- Generating PDF from XSL-FO files - generating PDF from a FO file
- XSL-FO Tables - adding tables to your PDF
- XSL-FO Images - adding images to your PDF
- XSL-FO SVG - adding SVG images to your PDF
- Using Triggers to Log Events - how to set up a trigger to log store, update and remove events on a collection
- Using Triggers to assign identifiers - how to use triggers to assign identifiers to new documents or new nodes
- Sending E-mail Email is one way to notify when a trigger has fired
XQuery Updates 
URL Rewriting 
- URL Rewriting Basics How to make your URLs look nice
Apache Ant Tasks 
General guidance 
Systems that Support XQuery 
Using native and hybrid XML databases that implement XQuery
- BaseX - Native open source XML Database with visual frontend
- DataDirect XQuery - Java XQuery engine supporting relational, EDI, flat files and XML input/output
- eXist - Open source native XML database
- DB2 pureXML - DB2 9.1 includes the pureXML feature
- MarkLogic Server - MarkLogic Server commercial XML Content Server
- Microsoft SQL Server 2005 -
- NetKernel - NetKernel
- Oracle Berkeley DB XML - Open source embedded storage management
- Oracle XML DB - Oracle Server 11g includes the XML DB (XDB) feature
- Sedna - Open source native XML Database
- Stylus Studio - XQuery mapping/editing/debugging, ships with Saxon (and SA) and DataDirect XQuery
- EMC xDB - EMC Documentum xDB commercial native XML database
- XQilla - Open source XQuery library and command line utility
- Zorba - Open source XQuery engine C++ implementation with C, Java, Php, Python, Ruby library bindings and command line utility
- Qizx - Open source and pro XQuery engine Java implementation
Debugging XQuery 
Other sources 
Function Libraries 
- FunctX XQuery Function Library by Priscilla Walmsley
Discussion Groups 
Key to symbols:
indicates an XQuery/Best practice