Computed Constructors

Generally, if you know the element or attribute name that you want to use in your results, you can use XML-like syntax as described in the previous sections. However, sometimes you may want to compute the name dynamically, so you cannot include the literal names in the query. In this case, you use computed constructors. This can be useful when:

  • You want to simply copy elements from the input document (regardless of name) but make minor changes to their content. For example, to add an id attribute to every element, or to move all the elements to a different namespace.

  • You want to turn content from the input document into element or attribute names. For example, you want to create an element whose name is the value of the dept attribute in the input document, without a predefined list of elements.

  • You want to look up element names in a separate dictionary, e.g., for language translation purposes.

You can use computed constructors for elements, attributes, and other kinds of nodes.

Computed Element Constructors

A computed element constructor uses the keyword element, followed by a name and some content in curly braces. The syntax of a computed element constructor is shown in Figure 5-2.

Syntax of a computed element constructor

Figure 5-2. Syntax of a computed element constructor

Example 5-13 shows a query that is equivalent to Example 5-3, except that it uses computed element constructors instead of direct ones. ...

Get XQuery now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.