Search code examples
dictionaryxquerydata-retrieval

Xquery: retrieving values from documents and put then into a single map


I am currently working with Xquery, and my goal is to retrieve values from different XML documents (1000+), all in the same folder (“myFolder”), and put then into a map.

The key would be a value “type” and the value in the key would be an unique identifier.

The original documents have a structure like the following:

<document>
     <!-- some siblings -- >
       <type>type1</type>
 <!-- some siblings -- >
         <id>id1</id>
 <!-- some siblings -- >
</document>

The final map would be like the following:

map  {
 type1: id1, id3, id4, id7(…)
type2: id2, id8(…)
type3: id5, id6(...)
}

I tried this code:

for $singleDoc in fn:collection($myURI ||"/myFolder/")

let $map= map:merge(for $t in distinct-values($singleDoc//type/string()) return
                                                                map:entry($t, $singleDoc//id/string()))

return $map

But it returned a map pro document, which is not the goal. If I then map:merge the resulting $map, it does not change anything.

Did I miss something in the path?

Thank you very much for your help!


Solution

  • Use

    map:merge(
      for $doc in fn:collection($myURI ||"/myFolder/")
      group by $type := $doc//type
      return map { $type : $doc//id }
    )
    

    or perhaps

    map:merge(
      for $doc in fn:collection($myURI ||"/myFolder/")
      group by $type := $doc//type
      return map { $type : data($doc//id) }
    )
    

    to have atomic id values instead of id elements in the map.