Inserting a New Node
The
insert
expression allows you to insert new nodes into XML documents. The XUF specification defines theinsert
expression aswhere:
(node|nodes)
can be one or more individual XML nodes; you can use either word regardless of the number of nodes being inserted.- target is the target expression. You use it both to identify into what you want the node inserted (an XML document, for example) and where. New nodes can be inserted at the start of the target (
as first
), and the end (as last
), orafter
orbefore
any node you specify.Note that if you do not specify placement in the target expression, DataDirect XQuery inserts new nodes at the end of the target in document order.
Example
In this example, for every user in users.xml, insert-nodes.xq adds 1000 shares of DDTEK stock to that user’s holdings. It creates a new
<holdings>
node for those users who do not already have DDTEK – or who are not already listed in the holdings.xml document – and writes the result to a new XML document. Note that theinsert node
expression specifies placement (as last
) within the target document.for $user in doc("/examples/xml/users.xml")/table/users let $ddtekShares := doc("/examples/xml/holdings.xml")/table/holdings[UserId eq $user/UserId and StockTicker eq "DDTEK"] return if( $ddtekShares ) then replace value of node $ddtekShares/Shares with $ddtekShares/Shares + 1000 else insert node <holdings> <UserId>{$user/UserId/text()}</UserId> <StockTicker>DDTEK</StockTicker> <Shares>1000</Shares> </holdings> as last into doc("/examples/xml/holdings.xml")/table, put(doc("/examples/xml/holdings.xml"),"/examples/xml/more-ddtek- holdings.xml")