1
votes

I have provided sample Xquery for insert and node replace Query.

My problem is If I am going to Execute the Query , its only insert the XML first.

even though i am going to execute second time the node will be replaced.

But I want the single execution it will be processed insert and update as well.

sample query :

xquery version "1.0-ml";
declare namespace html = "http://www.w3.org/1999/xhtml";
 let $a := xdmp:document-insert("/fo.xml", <a>1</a>)

let $b := xdmp:node-replace(fn:doc("/fo.xml")/a, <b>1</b>)

return ($a,$b)  
2

2 Answers

1
votes

Based on grtjn's answer you can do the following:

xdmp:document-insert("/fo.xml", <a>1</a>);
xdmp:node-replace(fn:doc("/fo.xml")/a, <b>1</b>);

Notice the semi-colon at the end of the lines. Those are statement separators. To understand more about statement separators (and transcations in general) you can refer to the following resource: https://docs.marklogic.com/guide/app-dev/transactions#id_11899.

1
votes

You cannot do that in a single statement. You either need to:

  1. use a multi-statement call (main statements separated by a semi-colon)
  2. do the update in-memory, and passing the updated content to the insert

Regarding 1:

The Application Developers Guide has a section about Semi-Colon as a Statement Separator, but in short it comes down to writing your query as follows:

xquery version "1.0-ml";
xdmp:document-insert("/fo.xml", <a>1</a>)
;
xquery version "1.0-ml";
xdmp:node-replace(fn:doc("/fo.xml")/a, <b>1</b>)

Regarding 2:

There are libraries that provide methods that operate very similar to the xdmp:node-* ones, but operate on content that has not yet been persisted to the database instead. You will need to download those first, and upload them to your modules database in order to use them. The best version I am aware of is https://github.com/ryanjdew/XQuery-XML-Memory-Operations. You can download and install that using MLPM. With that library you could write something like:

import module namespace mem = "http://maxdewpoint.blogspot.com/memory-operations" at "/ext/mlpm_modules/XQuery-XML-Memory-Operations/memory-operations.xqy";

let $a := <a>1</a>
let $b := <b>1</b>
let $updated-a := mem:copy($a) ! (
  mem:replace(., $a, $b),
  mem:execute(.)
)
return xdmp:document-insert("/foo.xml", $updated-a)

HTH!