Skip to main content

Patrick Tisseghem's Blog [MVP SharePoint]

Go Search
U2U Blog Center
U2U website
  

The Happy SharePoint Traveller

U2U Blog Center > Patrick Tisseghem's Blog [MVP SharePoint] > Posts > Include Items from Folders within your CAML Query Results
Include Items from Folders within your CAML Query Results

This week I am teaching an advanced SharePoint 2007 development course here in Brussels (next one is end of September). It's a lot of fun to go through all the material and I have invested a lot of energy in updating the lab material to provide an end-to-end scenario for the students to work out. All Feature-based of course; avoiding as much as possible to create stuff using the browser. Next week I'll teach the same course in Norway. It will be a busy week since I have more than 30 participants. And we already have a beer-drinking evening planned (of course J).

A student came with an interesting question regarding CAML queries: "If we execute a CAML query using SPQuery, can I have the items from subfolders included in the results returned?".

By default, only items out of the root folder are returned but there is a property you can set to get the results out of a folder (or all of them if you write a small loop).

SPSite site = new SPSite("http://moss.litwareinc.com/testsite");
if (site != null)
{
   SPWeb web = site.OpenWeb();
   foreach (SPList docLib in web.Lists)
   {
     if (docLib.Title == "Shared Documents")
     {
     foreach (SPFolder subFolder in  docLib.RootFolder.SubFolders)
     {
        SPQuery query = new SPQuery();
        query.Query = "<OrderBy><FieldRef Name='Title'/></OrderBy>";
       query.Folder = subFolder;
        System.Data.DataTable table = docLib.GetItems(query).GetDataTable();
     }
   }
 }
}

Thanks CAML girl for the suggestion J

Update: Michael Hofer has a good posting showing how to recursively get the items out of the folders using a CAML query.

Comments

Uhm, SpQuery.ViewAttributes anyone?

Have a look at Nick's comment to this post: http://www.sharepointblogs.com/michael/archive/2007/06/28/implementing-spsitedataquery-learning-by-doing.aspx

It is perfectly possible to recurse folders by setting
query.ViewAttributes = "Scope=\"Recursive\"";

(or if you also want to query the folder-type items, use "RecursiveAll"
at 24/08/2007 15:04

CAML Query help

Hi,
In my scenario, I need to write a CAML query to iterate to a folder structure hierarchically. There's no specific level of hierarchy. It is dynamic.
at 2/07/2008 14:35
Captcha

Enter the code shown above: *

(Note: If you cannot read the numbers in the above
image, reload the page to generate a new one.)