Inserting a New Node


The insert expression allows you to insert new nodes into XML documents. The XUF specification defines the insert expression as

insert (node|nodes) target 

where:

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 the insert 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")