XQuery/Saving and Updating Data

Motivation
You have some web forms (such as XForms) that need to save their data to your database. You want a single XQuery that will be used to save new data and update existing data. If a form is used to update an existing record, you can assume that it has an  tag in the XML document being saved. New documents will need to have a new document id created for them.

Method
We use HTTP POST data and scan for a specific element like id. If the record does not have an id element, we know that we must create a new record. Note that there is no sequence number generated in this example yet. If there is an id parameter, we will delete the old file and save the new data into the same file. Note that there is no backup or archive.

Sample Program to Store/Remove a single XML file
let $id := $my-doc/id

let $collection := 'xmldb:exist:///db/xquery-examples/save-test'

(: this logs you in; you can also get these variables from your session variables :) let $login := xmldb:login($collection, 'mylogin', 'my-password')

(: replace this with a unique file name with a sequence number :) let $file-name := 'test-save.xml'

return { if (not($id)) then (      let $store-return-status := xmldb:store($collection, $file-name, $my-doc)             return                New Document Created {$store-return-status} at {$collection}/{$file-name}        ) else (          let $remove-return-status := xmldb:remove($collection, $file-name)           let $store-return-status := xmldb:store($collection, $file-name, $my-doc)           return                Document {$id} has been successfully updated ) }

Sample Program to Insert an XML item at the end of an XML file
Sometimes you do not want to create a new XML file, but only save the results at the end of an existing XML file. This can be done using the XQuery update operations.

W3C Candidate Recommendation for XQuery Update Operations

eXist 1.2/1.3/1.4/1.5 syntax for XQuery Update Operations

For example, in eXist 1.2/1.3/1.4 the operation syntax is the following: