An XQuery script for listing the contents of collections in eXist-db

This ‘ll be a fairly straightforward post: an utility script for recursively listing all sub-collections and resources of collections in an eXist-db database (version 2.0). I often find myself looking for this, and stumbling my head against errors raised by insufficient resource permissions. Hence, this script has some checks built in that should avoid permission-related errors, and get following info for the resources available:

  • name
  • path inside the eXist db
  • (for collections) number of files or sub-collections
  • (for files) MIME type, file size
  • permission information: owner, group, permissions

The script can be downloaded here. As it’s rather small, I’ll give it here in full:


declare namespace ls="ls";
declare function ls:ls($collection as xs:string) as element()* {
  if (xmldb:collection-available($collection)) then
    (         
      for $child in xmldb:get-child-collections($collection)
      let $path := concat($collection, '/', $child)
      order by $child 
      return
        <collection name="{$child}" path="{$path}">
          {
            if (xmldb:collection-available($path)) then (  
              attribute {'files'} {count(xmldb:get-child-resources($path))},
              attribute {'cols'} {count(xmldb:get-child-collections($path))},
              sm:get-permissions(xs:anyURI($path))/*/@*
            )
            else 'no permissions'
          }
          {ls:ls($path)}
        </collection>,

        for $child in xmldb:get-child-resources($collection)
        let $path := concat($collection, '/', $child)
        order by $child 
        return
          <resource name="{$child}" path="{$path}" mime="{xmldb:get-mime-type(xs:anyURI($path))}" size="{fn:ceiling(xmldb:size($collection, $child) div 1024)}">
            {sm:get-permissions(xs:anyURI($path))/*/@*}
          </resource>
    )
  else ()    
};

let $collection := request:get-parameter('coll', '/db')
return
  <ls path="{$collection}">{ls:ls($collection)}</ls> 

If the script is stored in the db at ‘/db/myscripts/eXist_ls.xq’, it can be accessed at e.g.: http://localhost:8080/exist/rest/db/myscripts/eXist_ls.xq?coll=/db/apps, where the desired collection path can be passed with the ‘coll’ request parameter.

One Response to An XQuery script for listing the contents of collections in eXist-db

  1. sdreamworks says:

    Nice tuts.. thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: