Transforming Query Results


Transform expressions are used to create modified copies of nodes. Using copy, modify, and return clauses, transform expressions make a copy of an input document and then perform the XQuery and write the result to memory. Unlike other XUF update operations, transform expressions do not modify existing nodes.

Example – Replacing a Node Value

The transform-change-values.xq XQuery transforms the query result by increasing the number of <Shares> for user Minollo ($holding/UserId eq 'Minollo') by 20% (replace value of node... with... ($updatedHolding/Shares * 1.2)). A new root element, <table>, is created for the modified nodes that result from this XQuery.

declare option ddtek:serialize "indent=yes"; 
<table> { 
    for $holding in doc("../xml/holdings.xml")/table/holdings 
    return 
      if( $holding/UserId eq 'Minollo' ) then 
        copy $updatedHolding := $holding 
        modify 
          replace value of node $updatedHolding/Shares with    
          xs:integer($updatedHolding/Shares * 1.2) 
        return $updatedHolding 
      else 
        $holding 
} </table> 

Example – Inserting a Node

The transform-insert-nodes.xq XQuery performs two update operations depending on the query result:

declare option ddtek:serialize "indent=yes"; 
copy $newHoldings := doc("../xml/holdings.xml") 
modify 
  for $user in doc("../xml/users.xml")/table/users 
  let $ddtekShares := $newHoldings/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 $newHoldings/table 
return $newHoldings