XQuery
XQuery Examples Collection
editWelcome to the XQuery Examples Collection Wikibook! XQuery is a World Wide Web Consortium recommendation for selecting data from documents and databases.
Current Status
edit2019 refurbishment
editThere is a Github project to track issues with this book and collaborate amongst eXist db folk at least to bring this resource up-to-date.
Main tasks in the current refurbishment are to:
- get example code executable again
- remove complex case studies which use obsolete sources
- add XQuery 3.0 examples.
Search
editYou may search the book here:
New and Revised Articles
editAbout this Project
editThis 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 [1].
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.
Introduction
edit- 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 system.
- Naming Conventions - Naming standards used throughout this book.
Using XQuery
editCommon tasks in using XQuery with XML
- Executing a script - Executing an XQuery script
- Loading data - A tour of several different ways to load data into a native XML database
Example Scripts
editBeginning Examples
editExamples that do not assume knowledge of functions and modules.
- HelloWorld - A simple test to see if XQuery is installed correctly.
- FLWOR Expression - A basic example of how XQuery FLWOR statements work.
- Sequences - Working with sequences is central to XQuery.
- 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.
- 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
Intermediate Examples
editAssumes 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
- Queries on Tables - How to extract data from tabular data
- Namespace Constructors - how to dynamically add namespaces when constructing documents
Search
edit- 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
- 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
Transformations
editUsing XQuery to transform between XML and other representations
- Parsing CSV - Using FLWOR on sequences to parse CSV text.
Interaction
edit- 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.
- Adder - Retaining sate in interactions :Creating a web service that adds two numbers.
- Chaining Web Forms - Passing data from one web page to another using URL parameters, sessions or cookies
- Simple XForms Examples
- Incremental Search of the Chemical Elements - AJAX
- Sending E-mail - How to send an e-mail message from within an XQuery
Visualization
edit- Graph Visualization with Graphviz
- Google Chart Sparkline - Creating a Tufte Sparkline using the Google Charts API
- Google Chart Bullet Bar - Creating a bullet bar using the Google Charts API
Creating Custom Views
editThese 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
editXQuery 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
editUnlike 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
edit- 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
edit- 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
edit- Time Based Queries - using dates and times to limit search results
- Timing a Query - profiling how long a query takes
XML document kinds
editTEI documents
editText Encoding Initiative.
- TEI Concordance - How to build a TEI-based concordance
- TEI Document Timeline - Using Simile Timeline to visualize a TEI document
DocBook Documents
editOpenOffice
editOffice Open XML
editXML Schemas
edit
Processing Special Characters
edit- Special Characters - dealing with newlines and other special characters.
XQuery and other languages
editMusicXML
edit- Using Intermediate Documents Analysing MusicXML documents
- MusicXML to Arduino
Language Comparisons
editPython
editSQL
edit- XQuery SQL Module - Calling SQL from within your XQuery
- XQuery from SQL - Using XQuery to access a classic Relational database - Employee/Department/Salary
RDF/OWL
edit- List OWL Classes - A simple XQuery script that will display all the OWL classes in an OWL file
Language combination
editExcel
editJavaScript
edit- Navigating Collections - basic AJAX
- Employee Search - basic AJAX
- DOJO data - basic JSON
SQL
editXHTML + Voice
edit- Simple RSS reader
- XHTML + Voice Twitter Radio for Opera
XSLT
edit- XQuery and XSLT Executing an XSLT transform from within XQuery
Data Mashups
editAuthentication
edit- 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
editWikibook applications
editFreebase
edit- Freebase - use XQuery to get data via JSON from Freebase
Google Docs
edit- Google Docs - use XQuery to get data from Google Docs
Visualization
edit- Graph Visualization
- Graphing from RDF
- Dataflow diagrams
- Sequence Diagrams
- Example Sequencer - Step-by-step tutorial
Google Charts
editAlthough 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
editDigital 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
editPage 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
Mapping
edit- Google Geocoding
- /String Analysis#Location Mapping/ Mapping Car Registrations
- Flickr GoogleEarth
- Nationalgrid and Google Maps
- SMS tracker
Timelines
edit- 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
edit- 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
- Simile Exhibit Browser visualizations using the Simile JavaScript libraries
- Latent Semantic Indexing Finding the semantic distance between documents
Development Tools
edit- 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).
- Call Graphs - Generating an call graph as an SVG file from module introspection
- System Properties - getting a list of all standard and java system properties and their values
- Environment Variables - getting a list of all the external environment variables and their values
- Generating xqDoc-based XQuery Documentation - generating module documentation using the xqDoc commenting standard
Validation
edit- Validating a document - Validate a document with an XML Schema
- Validation using a Catalog - Using a Catalog file to validate documents
- Validating a hierarchy -
- Validation with Schematron - Apply specific rules to check a document
Path Analysis
edit- 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
Security
edit- 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
edit- 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
edit- Fizzbuzz
- Project Euler
- Topological Sort
- Slideshow
- Sudoku
- Pachube feed
- World Temperature records - conversion of text data formats to XML, indexing and data presentation
- UWE StudentsOnline
eXist db specific Functions and Configuration
editConfiguration
editInstalling modules
editSetting HTTP Headers
editModules
editdbutil
edit- Database Utilities - a set of database utility functions for database administration
compression
edit- Get zipped XML file
- Unzipping an Office Open XML docx file - Uncompressing and storing a docx file
eXgit
editModule for interacting with any git revision control system
EXPath File Transfer XQuery Extension Module
editThis module does both FTP, SFTP (using the SSH protocol) using a standardized and consistent format.
ftp client
editThis module allows you to interact with a remote FTP server on a remote system. It includes functions for listing, getting and putting files.
httpclient
editJSON
editLucene
editmath
editmemcached
editprocess
edit- Execute External Process - execute a shell command from within XQuery
request
edit- Getting URL Parameters
- Getting POST Data
- Checking for Required Parameters
- Manipulating URIs
- Parsing Query Strings
- Adder simple client-server interaction
scheduler
editsequences
edit- Sequences Module - three additional functions (map, fold and filter)
session
edit- Basic Session Management - the basics of session management including getting a setting session variables
subversion
edit- Subversion - how to update a subversion repository from within XQuery using the subversion client
transform
editutil
edit- 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()
validation
editxmldb
editxqdoc
editxslfo
editXSL-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
Triggers
edit- 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
edit- Inserting and Updating Attributes
- Updates and Namespaces - How updates can change serialization
URL Rewriting
edit- URL Rewriting Basics How to make your URLs look nice
Apache Ant Tasks
editReplication
editGeneral guidance
editAppendixes
editSystems that Support XQuery
editUsing 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
editOther sources
editFunction Libraries
edit- FunctX XQuery Function Library by Priscilla Walmsley
Discussion Groups
edit
Indexes
edit- Index of Application Areas - edited
Key to symbols:
indicates an XQuery/Best practice