Loading TOC...

xdmp:node-insert-child

xdmp:node-insert-child(
   $parent as node(),
   $new as node()
) as empty-sequence()

Summary

Adds a new last child to a node. For XML documents, only element nodes and document nodes can have children. For JSON documents, object nodes and array nodes can have children. Element nodes, object nodes, and array nodes cannot have document node children. Document nodes cannot have multiple roots. On-the-fly constructed nodes cannot be updated. The parameters must specify individual nodes and not node sets.

Parameters
$parent The parent node which will have a new child node.
$new The new child node to be inserted.

Example

(: create a document :)
xdmp:document-insert("/example.xml",
    <a/>);

(: insert a child of a :)    
xdmp:node-insert-child(doc("/example.xml")/a,
    <b>bbb</b>);

(: look at the new document :)
fn:doc("/example.xml")
 =>
<?xml version="1.0" encoding="UTF-8"?>
<a><b>bbb</b></a>

Example

(: create a document :)
xdmp:document-insert("/example.xml",
    <a/>);

(: insert an attribute as child of a :)    
  xdmp:node-insert-child(doc("/example.xml")/a,
    attribute b { "bbb" });

(: look at the new document :)
fn:doc("/example.xml")
 =>
<?xml version="1.0" encoding="UTF-8"?>
<a b="bbb"/>

Comments

  • Attempting to update an "external node" (for example, one that has been passed in from an invoking module via a "declare .... external;" declaration) will also throw an error, as this is not allowed, apparently. It would be good if the documentation reflected this limitation.
  • A common issue I've seen with developers updating nodes is not understanding the difference between updating a node in a document, in the database ... versus updating a node in a document that is in memory. For example; ----- xquery version "1.0-ml"; declare function local:f($x as element(test)) as element(test) { xdmp:node-insert-child($x, attribute new { "new" } ) }; let $x := <test blah="blah">some text</test> return local:f($x) ------ this code will fail with a 'Cannot update constructed nodes' error. This is because one is using xdmp:node-insert-child() to insert a node on the element contained in varible $x (which lives only in memory) versus a document held in the database. To fix your approach you can use the in-mem-update.xqy, which is in xquery-commons in github https://github.com/marklogic/commons/blob/master/memupdate/in-mem-update.xqy And as Alex Bleasdale shows, this in-mem-update.xqy module is built into MarkLogic is now built into MarkLogic http://blog.msbbc.co.uk/2011/07/marklogic-in-mem-update-example.html'
Powered by MarkLogic Server 7.0-4.1 and rundmc | Terms of Use | Privacy Policy