marklogic Very simple CRUD examples for XML documents Update the simple document


Example

We will now add some additional XML nodes to the "my-document" element and update the document. The snippet again contains comments to explain what is happening.

xquery version "1.0-ml";
(: We are preserving the same URI as we used originally :)
let $uri := "/stuff/mysimpledocument.xml"
(: Need to get the existing contents so we can append to those :)
let $orig-content := fn:doc($uri)/my-document
(: Documents need content. This is a simple XML node :)
let $new-content := 
  <notes>
    <note>Anything can be changed</note>
    <note>New content is added in this example, but we could replace it all too</note>
  </notes>
(: Now to build the new xml. There's lots of ways to do this :)
(: line 17 inserts the original contents into this new node construct :)
(: line 18 inserts the $new-content after the original contents :)
let $new-doc-content :=
  <my-document>
    {$orig-content/node()}
    {$new-content}
  </my-document>
(: Leave permissions untouched... :)
let $permissions := xdmp:document-get-permissions($uri)
(: Leave collections untouched... :)
let $collections := xdmp:document-get-collections($uri)
(: Now we're just going to insert this document in the database :)
let $insert := xdmp:document-insert($uri,$new-doc-content,$permissions,$collections)
return <message>Document {$uri} updated</message>

When executed, this returns the message

<message>Document /stuff/mysimpledocument.xml updated</message>

Now run the different read commands above to see the updated content. It should look like this:

<my-document>
    <body>Very simple example</body>
    <notes>
        <note>Anything can be changed</note>
        <note>New content is added in this example, but we could replace it all too</note>
    </notes>
</my-document>