XQUF

XQuery Update Facility (XQUF) is an extension to XQuery for updating XML documents in place, via insert, delete, replace, and rename expressions, a copy-modify-return transform expression, and an inline update expression usable inside a FLWOR. BaseX 693,830 is a program that supports XQUF.

Each example below updates the following document independently:

ch05-xquf-data.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<a>
   <b>Hello</b>
   <b>World</b>
</a>

insert node

The insert node expression adds one or more nodes into, before, or after a target node. Inserting a sequence of an attribute, a text node, and an element into /a appends them as the last children (attributes are added to the element regardless of position):

insert node (attribute {'id'}{5},'Yes!',<c/>) into /a
Output
as first into inserts a node as the first child of the target instead of the last (as last into is equivalent to a plain into):

insert node <c/> as first into /a
(: 'as last into' can be used too :)
Output
before inserts a node as the preceding sibling of a target node (after inserts it as the following sibling):

insert node <c/> before /a/b[2]
(: 'after' can be used too :)
Output

delete node

Removes one or more target nodes from the document:

delete node (a/b[1],a/b[2])
Output

replace node

Replaces a target node with a new node, including its name and content:

replace node a/b[2] with <c>Kitty</c>
Output
replace value of node keeps the target node's name and only replaces its value, so the replacement expression's string value becomes the new content while the element name stays unchanged:

replace value of node a/b[2] with <c>Kitty</c>
Output

rename node

Changes the name of a target node, keeping its content:

rename node a/b[1] as 'x'
Output

transform expression: copy ... modify ... return

A copy-modify-return expression binds a variable to a copy of a node, applies a sequence of update expressions to that copy inside modify, and returns the modified copy without touching the original document:

copy $v := /a
modify (
  rename node $v/b[1] as 'c',
  insert node ('Kitty') into $v/b[2]
) return $v
Output

update expression

An update expression applies update expressions to a node inline, e.g. within the return clause of a for, without a separate copy-modify-return block:

for $v in a/b
return $v update delete node text()
Output

Updating functions

A user-defined function can be marked as updating with the %updating annotation, allowing it to perform update expressions in its body: declare %updating function local:f() {...}. An updating function returns the "pending update list" of changes it makes rather than a regular value.