Search code examples
xpathxpath-3.1

Programmatically generate an array containing `null` values with XPath 3.1


I have a map representing a gaped array; the keys being the indexes of the array:

let $m := map{1: "val1", 2: "val2", 5: "val5", 7: "val7"} return

Now I would like to convert it into a real array, filling up the missing indexes with null:

array {
    ( 1 to max($m => map:keys()) ) ! (
        if ($m => map:contains(.)) then
            $m(.)
        else
            null(())
    )
}

But I get:

["val1", "val2", "val5", "val7"]

Instead of my expected output:

["val1", "val2", null, null, "val5", null, "val7"]

Solution

  • I'm rather confused by your question. There is no such value as "null" in the XDM data model, and there is no function null() as in your example. The XDM equivalent to a JSON null is an empty sequence.

    Generating an array that contains non-singleton members (including (), which serialises to JSON null) is tricky in XPath 3.1. One way is to use array:for-each:

    array{1 to max(map:keys($m))} 
      => array:for-each($m)
    

    This takes advantage of the fact that array:for-each expects a function, and a map is a function.