This code sample is adapted from Clifford B. Anderson and Joseph C. Wicentowski, XQuery for Humanists (College Station: Texas A&M University Press, 2020), 221. Download this code sample in its raw form. View the source on GitHub.

xquery version "3.1";

declare %updating function local:add-timestamp($doc) {
    if ($doc/book/timestamp) then
        replace value of node $doc/book/timestamp 
            with fn:current-dateTime()
    else
        insert node element timestamp { 
            fn:current-dateTime() } 
        into $doc/book
};

local:add-timestamp(fn:doc("book.xml"))