bhylu.com

Advertisements

XML XQuery Grouping and Maps

XQuery 3.1 supports grouping and maps for structured results. A map is a value that can hold lookup entries; it is not an XML element or a database table.

How it works

Group packet tuples by their category, calculate a total and build a map entry for each group. map:merge combines the entries, and lookup reads a value by key. Use deterministic sorting when serializing a report because map iteration order is not a presentation contract. This example returns one explicit lookup, making its expected output independent of implementation-specific map display formatting.

Run the code

Use Saxon-HE 12.9 with Java 21 or newer. Download the official Java distribution, keep its dependency JARs in a lib folder, and save exchange.xml beside the example. On Windows the command is java -cp "lib/*" net.sf.saxon.Query -s:exchange.xml -q:query-grouping.xq !method=text. Use your actual Saxon JAR folder; the official archive may put dependencies in a nested lib directory, so include both folders in the Java classpath when needed. Saxon-HE does not supply XSD schema-aware processing or the XQuery Update Facility.

Download the complete query-grouping.xq source. Keep each lab in its own folder. Sources are served as text, not as public executable server scripts. Review the starting setup.

Example

query-grouping.xq

xquery version "3.1";
declare namespace map="http://www.w3.org/2005/xpath-functions/map";
let $totals := map:merge(
  for $packet in /exchange/packet
  group by $category := string($packet/category)
  return map:entry($category, sum($packet/quantity ! xs:integer(.)))
)
return $totals?herb

Expected result

7

The herb group contains quantities zero and seven, so its total is seven. Grouping changes the variable bindings: packet represents the members of the current group after the group-by clause. Read that scope change carefully.

Check the exact contract in the XML specification, XPath 1.0, the XSD 1.0 primer, lxml validation documentation and Saxon’s processor documentation.