Search code examples
xquerymarklogic

How to create a folder on the file system if it does not exist when saving files


Given the below XQuery code generating paths and saving files based on data in MarkLogic database, how can I create the file system folder if it does not exist without getting an exception?

for $doc in collection("http://example.com/stuff")
let $folderName := name($doc/Envelope/*[1]) 
let $folderPath := concat("c:\temp\", $folderName, "\")
let $fileName := concat($doc/Envelope/*[1]/*:Code/text(), ".xml")
let $fullPath := concat($folderPath, $fileName)  

(: Create the folder at $folderPath if it does not exist :)

return xdmp:save($fullPath,$doc)

Solution

  • AFAIK there is no "folder exists" function, confusingly filesystem-file-exists actually works for folders too, so the answer would be:

    for $doc in collection("http://example.com/stuff")
    let $folderName := name($doc/Envelope/*[1]) 
    let $folderPath := concat("c:\temp\", $folderName, "\")
    let $fileName := concat($doc/Envelope/*[1]/*:Code/text(), ".xml")
    let $fullPath := concat($folderPath, $fileName)  
    
    let $_ := if(xdmp:filesystem-file-exists($folderPath)) then () else xdmp:filesystem-directory-create($folder)
    
    return xdmp:save($fullPath,$doc)