Dynamic constructors

In the previous sections we could seen several ways to reach the nodes. However, the XQuery language has the tools to create nodes dynamically (during run-time) as well. Its important to highlight the node identity again because the nodes created by the constructors always have a new identity.

While XQuery always flatten the sequences the nested application of node constructors is the only way to hierarchically structure values in XQuery. (It makes it possible to optionally replace an XSLT transformation with XQuery.) XQuery expressions may construct nodes with new identity of all seven node kinds known in XML. XQuery node constructors come in two flavors:

The most important constructors:

The XQuery element constructor is the most flexible because the content sequence is not restricted and may have type item*. The construction consists the following steps:

  1. Consecutive literal characters yield a single text node containing these characters.

  2. Expression enclosed in {···} are evaluated.

  3. Adjacent atomic values are cast to type string and collected in a single text node with intervening " ".

  4. A node is copied into the content together with its content. All copied nodes receive a new identity.

  5. Then, adjacent text nodes are merged by concatenating their content. Text nodes with content "" are dropped.

// Evaluate the expression below:
count(
<x>Fortytwo{40 + 2}{ "pi",3.1415,<y><z/></y>,("","!")[1] }</x>/node()
)

We need to take care on one thing during the construction of the content: well-formed element content is needed. (I.e.: no two attributes of the same element may share a name and attribute nodes precede any other element content.) Finally, construction establishes document order!