to the main page about the tutorial  THE XML REVOLUTION  -  TECHNOLOGIES FOR THE FUTURE WEB back up next

FLWOR expressions

The main engine of XQuery is the FLWOR expression: A complete example is:
for $d in document("depts.xml")//deptno
let $e := document("emps.xml")//employee[deptno = $d]
where count($e) >= 10
order by avg($e/salary) descending
return
  <big-dept>
     { $d,
        <headcount>{count($e)}</headcount>,
        <avgsal>{avg($e/salary)}</avgsal>
     }
  </big-dept>
The combined result is in this case a list of departments with at least 10 employees, sorted by average salaries.

General rules:

Note the difference between for and let:
for $x in /company/employee

generates a list of bindings of $x to each employee element in the company, but:

let $x := /company/employee

generates a single binding of $x to the list of employee elements in the company.

This is also sufficient to compute joins of documents:
for $p IN document("www.irs.gov/taxpayers.xml")//person
for $n IN document("neighbors.xml")//neighbor[ssn = $p/ssn]
return
  <person>
    <ssn> { $p/ssn } </ssn>
    { $n/name }
    <income> { $p/income } </income>
  </person>

back COPYRIGHT © 2000-2003 ANDERS MØLLER & MICHAEL I. SCHWARTZBACH next