N. America: 800 876 3101 | World: 44 (0) 1753 218 930

How can I query all documents in a folder?

You can use the fn:collection() function to query all documents in a folder. DataDirect XQuery™ allows you to specify regular expressions to match file names, provides the possibility to fetch all documents recursively in nested folders, and the possibility to sort the result. The syntax that DataDirect XQuery™ accepts for the fn:collection() function argument when dealing with retrieving files from folders is this:

collection("directory_url(?option(;option)*)?")

where:

  • directory_url is a URL referencing a directory. The URL must use the file:// scheme.
  • option is {(select="REGEX") | recurse={yes | no} | (sort=[a,t,r]+) | (xquery-regex=(yes|no))}

More details available in the DataDirect XQuery™ product documentation.

In the following example, suppose you have a number of XML files stored in the directory named books. Each of the files contains information about one book, and you want to create a single XML document that contains a list of all your books.

<books> {
for $book in collection("file:///c:/books?select=*.xml ")
return
  <myBook>{$book/book/title}</myBook>
} </books>

The result would look something like this:

<books>
  <myBook>
    <title>Emma</title>
  </myBook>
  <myBook>
    <title>Pride and Prejudice</title>
  </myBook>
  . . .
</books>

If the books directory contained sub-folders with other XML documents, then you would need to change the XQuery to:

<books> {
for $book in collection("file:///c:/books?select=*.xml;recurse=yes")
return
  <myBook>{$book/book/title}</myBook>
} </books>


Next Question!

In what order does fn:collection() return documents?

Submit Your DataDirect XQuery Tip or Trick

Tell us your XQuery Tip or Trick – if it gets published on our site, you’ll receive a

$10.00 Amazon.com
Gift Certificate!

Submit your tip or trick today.