bhylu.com

Advertisements

XML XQuery Node Constructors

Direct constructors build XML result elements around selected values. A computed constructor is useful when the node name is chosen by a controlled expression.

How it works

Enclosed expressions use braces to insert values into a constructed element. The new node is a result, not a change to the source document on disk. Adding content in the returned value is different from the XQuery Update Facility, which Saxon-HE does not provide as an update service. Keep controlled vocabulary names separate from untrusted values and serialize the result according to the consumer’s contract.

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-constructors.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-constructors.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-constructors.xq

xquery version "3.1";
let $result := <available>{
  for $packet in /exchange/packet[@available="true"]
  return <seed id="{$packet/@id}">{$packet/name/string()}</seed>
}</available>
return string-join($result/seed ! concat(@id, ":", string(.)), ";")

Expected result

p1:Marigold;p3:Basil

Two new seed nodes are created inside available. The final expression reads the constructed result into a concise checked output. The source still contains all three original packet elements.

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