Updating multiple nodes in xml with xquery and xdmp: node -replace

I want to update an XML document in my xml database (Marklogic). I have xml as input and you want to replace every node that exists in the target xml.

If node does not exist, it would be great if it were added, but it could be a different task.

My XML in the database:

<user>
  <username>username</username>
  <firstname>firstname</firstname>
  <lastname>lastname</lastname>
  <email>email@mail.de</email>
  <comment>comment</comment>
</user>

The value of $ user_xml:

<user>
  <firstname>new firstname</firstname>
  <lastname>new lastname</lastname>
</user>

My function so far:

declare function update-user (
    $username as xs:string,
    $user_xml as node()) as empty-sequence()
{
    let $uri := user-uri($username)
    return
        for $node in $user_xml/user
        return 
            xdmp:node-replace(fn:doc($uri)/user/fn:node-name($node), $node)
};

First of all, I can’t sort out $user_xml/user. If I try to iterate through $user_xml, I get an exception

arg1 does not have type node ()

But maybe this is the wrong approach?

Does anyone have a code example on how to do this?

+3
source share
1 answer

I have to answer myself:

declare function update-user (
$username as xs:string,
$user_xml as node()) as empty-sequence()
{
let $uri := user-uri($username)
return
    for $node in $user_xml/*
    let $target := fn:doc($uri)/user/*[fn:name() = fn:name($node)]
    return
        if($target) then
            xdmp:node-replace($target, $node)
        else
            xdmp:node-insert-child(fn:doc($uri)/user, $node)
};

, , - /user/*[fn:name() = fn:name($node)]?

+5

Source: https://habr.com/ru/post/1781671/


All Articles