OpenLLM-France/wikimedia huggingface dataset:
# XML - Managing Data Exchange/XPath/Answers

XPath Chapter => XPath
XPath Exercises => Exercises
XML

## Exercises

In this exercise, you will modify the xsl-tree.xsl file we saw in chapter 8 XPath to...
* Print the name attribute of every bigBranch element with thickness set as ‘thick’.
* Print the name of the parent of each bigBranch.
* Print the color of all leaves with a color attribute.

## Answers
### 1. Print the name attribute of every bigBranch element with thickness set as ‘thick’

xsl-tree1.xsl
* <?xml version="1.0" encoding="UTF-8"?>
* <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
* <xsl:output method="html"/>
* <xsl:template match="/child::trunk">
* <html>
* <head>
* <title>XPath Tree Tests</title>
* </head>
* <body>
* <xsl:for-each select="child::bigBranch[attribute::thickness='thick']">
* <xsl:call-template name="print_out"/>
* </xsl:for-each>
* </body>
* </html>
* </xsl:template>
* <xsl:template name="print_out">
* <xsl:value-of select="attribute::name"/>
* <br/>
* </xsl:template>
* </xsl:stylesheet>
Output
* bb1

### 2. Print the name of the parent of each bigBranch

xsl-tree2.xsl
* <?xml version="1.0" encoding="UTF-8"?>
* <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
* <xsl:output method="html"/>
* <xsl:template match="/child::trunk">
* <html>
* <head>
* <title>XPath Tree Tests</title>
* </head>
* <body>
* <xsl:for-each select="child::bigBranch">
* <xsl:call-template name="print_out"/>
* </xsl:for-each>
* </body>
* </html>
* </xsl:template>
* <xsl:template name="print_out">
* <xsl:value-of select="parent::node/attribute::name"/>
* <br/>
* </xsl:template>
* </xsl:stylesheet>
Output
* the_trunk
* the_trunk
* the_trunk

### 3. Print the color of all leaves with a color attribute

xsl-tree3.xsl
* <?xml version="1.0" encoding="UTF-8"?>
* <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
* <xsl:output method="html"/>
* <xsl:template match="/child::trunk">
* <html>
* <head>
* <title>XPath Tree Tests</title>
* </head>
* <body>
* <xsl:for-each select="descendant::leaf[string(attribute::color) != '']">
* <xsl:call-template name="print_out"/>
* </xsl:for-each>
* </body>
* </html>
* </xsl:template>
* <xsl:template name="print_out">
* <xsl:value-of select="attribute::name"/>, <xsl:value-of select="attribute::color"/>
* <br/>
* </xsl:template>
* </xsl:stylesheet>
Output
* leaf1, brown
* leaf5, purple
* leaf9, black
* leaf14, red
* leaf17, red
XPath Chapter => XPath
XPath Exercises => Exercises
# XML - Managing Data Exchange/XPath/Exercises

XPath Chapter => XPath
XPath Answers => Answers
Below are exercises you can do to hone in on your XPath skills. Use the tree.xml file and xsl-tree.xsl to do the following:

## XPath Tree Example

Modify and copy the xsl-tree.xsl file and rename the copies, indicating the question number.
   * Print the name attribute of every bigBranch element with thickness set as ‘thick’.
   * Print the name of the parent of each bigBranch.
   * Print the color of all leaves with a color attribute.
XPath Chapter => XPath
XPath Answers => Answers
# XForms/Pie Chart
## Motivation

You want to use range controls to interactively change a drawing such as a pie chart. In this case we use a JavaScript library that modifies an SVG image. The data for the pie chart is kept in an instance in the model.

## Link to Working XForms Application

XForms Example of Dynamic Labels

## Discussion

This example a nice clean way to interactively change a value just using the mouse. No keyboard required. Here is the sample for the first range control:
This is an example of how an instance document can be used as the interface to an external component in a form. You just have to put the data in the instance and tell the application to get the data.

## Credits

This example was originally inspired by the 1040 tax form example on the Mozilla web site. The JavaScript for drawing the pie chart was taken from that example.
# XForms/Open Selection
## Motivation

You want to have a control that suggests a set of values in a drop-down list but also allows a user to type in their own value.

## Method

Just add the attribute selection="open" to your select1 control:

## Screen Image

Note that although a list of possible countries is listed, the user can type in any country that is not on this list.

## XForms Application

Load XForms Application
The following example allows you to select a country code or enter your own country code:

## Discussion

Very often you want to suggest values to the user to ensure consistency of data entry. The problem is that there are sometimes exceptions to a small list of items and the open selection control allows these exceptions to be entered.
One challenge of using this control is to let the user know they can enter an exception. You may have to add instructional text on the form such as "type value in this field if it does not appear on this list".
# XForms/Output and Links
## Motivation

You want to display a repeated set of URLs in a section of your form. Each URL is created by concatenating a base URL and a URL parameter.

## Method

The equivalent of the HTML anchor tag (<a>) in an XForms application is the <xf:load> element.
If in a web page, you want your output to appear like this:
in an XForms application each anchor will be xf:load.
Your input instance is like the following:

## Discussion

With XForms it is not possible to create dynamic links inside a repeat using a combination of output, value and concat. This would also impact the ability to notify the user that is navigating away from a form.
There are two ways to display a list of links. Both use a trigger with the button appearance turned off. The first uses a load after setting a temporary instance. The second uses a submit/submission combination.

## Using load

You can also use the load element as the element.

### Link to XForms Application

Load XForms Application

### Sample Program

The following program displays a list of links in a horizontal row. Each link has a label and a URL suffix that is extracted from an instance document.

## Acknowledgment

This solution was posted to the Mozilla XForms development newsgroup by John Clark on February 27th, 2008.

## Using Submit and Submission for Links

As an alternative strategy you can replace a form by using the submission statement with a replace="all" attribute. You can then style the submission button using appearance="minimal" and make the button look like a link:
The only disadvantage of this solution over using standard links is that the URL does not display in the status bar. This problem can be mitigated by using the xf:hint element within the label. This text will display when the user hovers over the link.
This method also allows you to interrupt the submission, check for changes in instance data and display warning messages before a form is unloaded.
# XForms/Picoforms
## Getting XForms to work with Picoforms

Picoforms is commercial XForms client that is designed to work with mobile phones and IE 6.0 as a plugin.
To get IE to see the forms you have to do the following:
If your forms are stored in the server with an XHTML extension you must
* Make sure that IE knows to render .XHTML files as html file types. This can be done by using the registry edit tool.
* Add the following processing instruction for picoforms AFTER the html element

## IE 6.0 Registry MIME-Type Fix

To change the IE registry to allow IE to know that .xhtml files should be rendered as html. To do this do the following. From the Windows start menu click Start/Run. Enter "regedit" and press enter. Use the Registry browser to navigate to the HKEY_CLASSES_ROOT folder and then find the MIME/Daatabase/Content Type folder.
From their add the following:
Binding for xhtml files:
Binding for xq files:
The CLSID above is for HTML rendering. You can copy this from the .htm MIME-type. If you want it to render in xml use the binding for XML files.

## Sample HTML Header

Note that if you are using eXist to generate your forms you need to put the PI inside braces and serialize as html.
Also, make sure if you make changes you should be sure to use SHIFT-reload to clear the IE cache.

## CSS Issues

Note that IE6 does not recognize the @namepsace directive in CSS files. These CSS files will need to be converted use xf\: instead of the CSS | standard.

## References

Picoforms Web Site
# XForms/Outline Editor
## Motivation

Sometimes you want to allow a user to be able to add properties to a list that change the appearance of the item in the list. In this example, the level of indentation is controlled by an attribute in a list called the "level" which is the indentation level in an outline view.
Note: This program was based on an example Kurt Cagle posted on the Mozilla XForms developer news group. This example posted with his permission.

## Link to working Program

Tree Editor

## Sample Program

Here is a sample outline-editor program. If you want to test this, be sure to use the edit view to copy the text. This file includes several tab characters that do not display correctly in the view mode.

## Discussion

The structure of this program uses custom events. Note that in the model there are a series of actions, each with their own event name:
These events are called directly inside of a trigger like this:
Note that the target attribute is the name of the model that the events are located.
Although actions can be tucked directly into a trigger, sometimes action are more logically grouped with instance data and should be placed directly in the model. This also allows other events need to reuse these actions, so it is a good ideal to put reuseable actions directly in a model

## References

A version of this program was initially posted by Kurt Cagle on the Mozilla XForms newsgroup.
# XForms/Multiple Uploads
## Motivation

You would like the user to be able to attach multiple files to a form.

## Method

We will use the <xf:repeat> around the upload control:

## User interface notes

* The delete trigger will only be visible after the second upload is shown.
* This interface shows the file name and size in bytes. The mime-type could also be shown
* You can add any number of files
* You can delete any row by selecting the "Delete" button
* You can re-add a file using the red X
The files will be uploaded to the server in an async process.
Tested on Orbeon 4.3
# XForms/NIEM to XForms
## Motivation

You want to convert a constraint XML Schema that uses subsets generated by the US National Information Exchange Model (NIEM) directly into an XForm

## References

Article by Dan McCreary on IBM Developerworks
# XForms/Player Specific Instructions
## FireFox Extension

Directions for installing the FireFox extension are listed here.
Make sure your XForms files have the .xhtml extension.
This document describes how the FireFox extension adheres or differs from the formal W3C specification.

## FormFaces

FormFaces is a JavaScript implementation of XForms. To use it you can do the following:
First download the FormFaces JavaScript Library from the from faces web site http://www.formfaces.com/.
To use the FormFaces solution you will need to do two things. First add the following line to all your forms:
Second you will need to download the 85K Javascript file called "formfaces.js" and put it in the same directory that you are running the program.

## formsPlayer

formsPlayer allows users to view XForms pages within Internet Explorer, on Windows. The processor was the first to fully implement the XForms 1.0 standard, and continues to lead the way by implementing the latest Working Draft of XForms 1.1. For details on how to install formsPlayer and set up a development environment, and then use this to follow a detailed Introduction to XForms tutorial, see Programming formsPlayer and XForms. The tutorial includes in depth discussion of two forms; one that saves bookmarks to del.icio.us, and another that searches Flickr.

## X-Smiles

X-Smiles is a browser that includes XForms support. See http://www.x-smiles.org/ for details. X-Smiles allows many of the programs in this book to run without modification. X-Smiles does not support some XHTML standards. For a full report of what features are working in X-Smiles see this link: http://www.x-smiles.org/features_xforms.html
# XQuery/Sudoku

Sudoku solver in XQuery

## A Puzzle

A sudoku puzzle can be expressed in matrix form. Here is part of one from a Times book of sudokus.

## The Main script

The main script is passed a URL referencing the problem XML file. The matrix format is converted to a sequence of cells, the puzzle solved, the resultant cell list converted back to a matrix and the matrix printed. The elapsed time of the solution search is computed and displayed after the initial problem and the solution.

## Functions

This module defines the necessary functions to support a brute force, depth-first search of the solution tree. Two representations of a sudoku puzzle are used here:
The algorithm starts with the cell list representation. The number of possible solutions to every empty square is calculated. If there there is a cell with only one value, that cell is added to the list of cells and the algorithm continues. If there is more than one possible value for a cell, the algorithm iterates over the possible values, positing that each in turn is the correct value. If there is no possible value, that partial solution is infeasible and that solution path is abandoned, returning null and the next possible cell value will be tried.

## Execution

With a few problems from the Times book of Sudoku problems:
* solve Puzzle 1
* solve Puzzle 2
* solve Puzzle 100 - the last

## Discussion

This code requires eXist 1.3 or above to run.
# XQuery/TEI Concordance
### Motivation

You want to build a multi-lingual concordance from parallel texts already in the TEI format (see http://www.tei-c.org/ )

### Architecture

There are three steps in this example:
* preprocessing the texts to enable easier indexing, which is done in XSLT 2.0
* querying the text to return a tei:entry (see http://www.tei-c.org/release/doc/tei-p5-doc/en/html/DI.html ) which is done in XQuery
* processing the tei:entry into HTML which is done in XSLT 1.0 in the browser
In this particular example the languages in use are English and te reo Māori. It assumes that structural tags have 'n' attributes with urls pointing to the original source of the data.

### Preprocessing the text

This stylesheet splits the text into words (tei:w see http://www.tei-c.org/release/doc/tei-p5-doc/en/html/ref-w.html ) and records on each a 'lemma' or normalised form of the word and the language it's in. These are re-calculated to allow indexes to be built of them.

### Querying the text

The query builds a single <tei:entry> tag containing multiple <tei:cit>, one for each hit. A processing instruction is used to associate the TEI with a stylesheet.

### Transformation to HTML

The TEI is transformed into HTML in the browser following the processing instruction:
# XQuery/Time Based Queries
## Motivation

You want to find items in a collection based on date-time information.

## Method

By default, XML files use standard ISO dateTime structures to store temporal information. There are two main XML data types related to storing time:
xs:date - for storing just the date in YYYY-MM-DD format. xs:dateTime - for storing both the date and time.
There are many other structures for storing just year, month, day and time etc. but this example will only cover dates and dateTimes.

## Sample Event Structure

In the following example we will store "event" data using a simple date structures. Events will have just a single start date or a date range with a start date and end date:
You can find all events that are occurring during any specific point in time with the following xquery structure.
Source from events-at-time.xq
You can also set up very fast searches based on the date-time structures even for large collections of 100,000 items after you learn how to configure range indexes on XML xs:dateTime structures. See: http://www.w3.org/TR/xmlschema-2/#dateTime how date-time structures work.

## References

The following page has instructions on indexing:
http://exist-db.org/exist/apps/doc/indexing.xml
And make sure to read section 2.2 on range indexes.
I would also use the xs:date and xs:dateTime structures in your range indexes.
Your collection configuration file (see http://exist-db.org/exist/apps/doc/indexing.xml#idxconf) might have the following lines if you are tracking document creation and modified dateTimes:
Note that all eXist collections and resource also have both these dates in their metadata. You can use the xmdb module to get these timestamps:
xmldb:created
xmldb:last-modified

## Other Resources

* Timeline mashups in this Wikibook
* Gantt Chart using JQuery
* Timeline SVG reports
* Gantt Charts from XML data using Anychart
# XQuery/Synchronizing Remote Collections
## Motivation

You want to update items on collections that are new or newer than another collection.

## Method

Many database store creation dates and last-modified dates along with resources. These dates can be used to see if a local collection is out of sync with a remote collection. An XQuery script can be written that will only list the new files or files that are newer then the creation date on your local collection.
For the eXist database, here are the two functions that are used to access the timestamps.
Where:
For example:
Will return the date and time that the file myfile.xml in the collection /db/text was last modified. The format of the timestamp is the XML Schema dateTime format:
For example, this indicates the time is 7:50 am on June the 4th, 2009 for Central Standard Time which is 5 hours behind Coordinated Universal Time (UTC).

## Sample Recursive Collection Last Modified Function

You can combine the xmldb:last-modified function with another function xmldb:get-child-collections($collection) that returns all of the child collections of the current collection. By calling itself using tail recursion you can find all the last modified dates within a collection and all its subcollections.
Here is a sample XQuery function that returns a list of all the last-modified date-times of the resources in a collection and all of the subcollections under it.
Note that two attributes are added to each resource. One is the resource id which must be unique in each collection an the other is the date the resource was last modified.

## Sample Driver

You can call this function by simply passing the collection root you wish to start at.
This returns the following file:

## Driving Syncs with Apache Ant

You can now use these transforms to create batch files that will transfer only the files that have changed or are new.
Many databases provide Apache Ant tasks that have functions that extract and store operations.
Here is a sample Apache ant target that does an extract on a local file and stores it on a remote file.
Note that the following properties must be set in this Ant file.
# XQuery/The Emp-Dept case study

The Employee-Department case study used in the comparison of XQuery from SQL is used here to explore the XQuery/SPARQL pairing.

## Conversion to RDF

Taking as the starting point the XML documents defining the three tables:
* Emp
* Dept
* Salgrade
These documents are converted to RDF using an XQuery script guided by a mapping file. The generated RDF is cached. and accessed by an XQuery script to de-reference the resource URIs.
Individual resource URIs are re-written in Apache to calls on an XQuery script which retrieves the fragment of RDF from the cached file. Thus;
* an employee
* a department
* The full RDF (need to change the rewrite rule to fix this strange uri)
This should be replaced by a query on the SPARQL endpoint.

## RDF browsing

This RDF can be browsed with and RDF browser such as Disco , OpenLink RDF browser OpenLink Data Explorer or Tabulator as an add-in to Opera or Firefox

## Querying with SPARQL

The RDF can be queried with SPARQL. The same queries uses in the SQL /XQuery example are expressed in SPARQL in this tutorial
# XQuery/Time Comparison with XQuery
## Motivation

You have two identical lists of items with timestamps. You want to compare the items to see what items are newer.

## Method

We will write a function that compares the timestamps of the items in two lists.

## Sample Test Driver

Execute

## Collating

Alternatively, two ordered lists can be collated to derive a set of updates. Here the items are wrapped in a div to carry the added information about the merge. Items in list1 but not list2 are flagged as new, items in list 2 but not list 1 as to be deleted and items which are newer in list 1 than list 2 as newer.
The sample data and main script are changed slightly:
Execute
# System Properties

You can get a system property by using the util:system-property function

## See Also

XQuery/Environment Variables
# XQuery/Tag Cloud
## Counting Words

A tag cloud (or weighted list in visual design) is a visual depiction of user-generated tags, or simply the word content of a site, typically used to describe the content of web sites.
One method of creating a tag cloud is to create a list of the words in a document, count the number of occurrences of each word, and depict the more frequently occurring words with a larger font size than the words that occur less frequently.

## Counting the total number of words in a text object

To get a feeling for one of the basic techniques, let's examine Jon Robie's code, which takes all of the text nodes in a document, strings them together, splits them into a sequence of "words" (tokenizing by whitespace, punctuation, or the 'nbsp' entity), and counts the number of resulting words:
Note that the string-join function here takes an input sequence and returns a single string that is separated by single spaces (the second argument of string-join).
If you want to see what this routine treats as a "word" in your document, use the following variation.
Another variation is the word-count function found at xqueryfunctions.com:
This version uses the \W+ regular expression (which matches non-alphabetical characters) to return word tokens.

## Counting Keywords

Kurt Cagle suggested the following XQuery for counting keywords:

### This Returns the Following
## Creating a Tag Cloud

From this you can create a Tag Cloud or word density map such as the "Popular Tags" link on the flickr web site Flicker Popular Tags
# XQuery/Timelines of Resource
## Motivation

You want to create a timeline using the creation and modification dates of a collection.

## Method

Many file systems and XML databases such as the eXist database automatically keep two dates associated with each resource. One is the creation date and the other is the date the resource was last modified. These dates are required for many systems that perform incremental backups of resources.
We can use these dates to automatically create a timeline report of one or more collections. These reports can server as audit trails and can help you find out who changed what and when.
Here are two of the functions that we will use in these examples:
Note that you can also use the created function with a single parameter to see when a collection was created.
Our query will take a single parameter, the database path expression to the collection we wish to create a timeline for. Our timeline will then display the creation and modification dates for this collection.
Here is a sample query fragment that lists all child of the resources in a collection and formats the data according to the timeline event XML structure.
This will return a file of in the following format: