XQuery/Validating a hierarchy

Whilst schema validation can check for some aspects of model validity, business rules are often more complex than is expressible in XML schema. XQuery is a powerful language for describing more complex rules.

One such rule is that a relationship should define a tree structure,for example, the relationship between an employee and her manager.

Consider the following set of employees:

Fred Bill Joe Bill Alice Joe Bill

The criteria for a valid hierarchy are:
 * 1) one root (the boss);
 * 2) every employee has at most one manager;
 * 3) every employee reports finally to the boss;
 * 4) there are no cycles

In XQuery we can define the management hierarchy from the boss down to an employee as :

The function is initially called as

The hierarchy is built up as a parameter to allow cycles to be detected.

Finally, the condition for the management structure to be a tree is