Querying subfolders in SharePoint lists using SPAPI and GetListItems()

Standard

This took a while to figure out. I’ve been trying to query the SharePoint lists service using getListItems().

Getting something from inside one folder is easy — you just set the queryOptions parameter to be <QueryOptions><Folder>folderName</Folder></QueryOptions>.

This works and returns items fron within that folder. But what about subfolders?

One would expect it to be simple — but it is not, replacing folderName with folderName\subFolder does not work — it still returns items from within folderName.

The solution is simple but non-obvious. For sub-folders, you have to include the name of the list as the first path element — so the query becomes <QueryOptions><Folder>listName\folderName\subFolder</Folder></QueryOptions>

This doesn’t seem to be covered in any documentation, and is non-obvious, inconsistent behaviour. It resulted in a lot of wasted time for me. Unsurprising really for the over-complex, proprietary, non-standard mess that is SharePoint.

5 thoughts on “Querying subfolders in SharePoint lists using SPAPI and GetListItems()

  1. Mark

    thanks man, I was also having a hard time with this – i’m hating sharepoint at the moment but at least your article saved me a struggle.

  2. devin

    Thanks a bunch. This helped me a lot too.
    Also just to note, I was running this using the folder path from another query and when getListItems returns the results “ows_FileDirRef” has the folder id added to the front like this “17;#listName\folderName\subFolder”, so if you want to use it you have to remove it with something like “result.Substring(result.IndexOf(‘#’)+1)”

  3. Zafer

    It’s not working it returns all items and folders from the whole list, its like its been set to be recursive, any idea ?

    thanx heap

  4. just use the path of folder from document ibrary i.e.
    If document ibrary = doclib then use as:

    queryOption.InnerXml = “doclib/folder/sub_folder/”;

  5. just use the path of folder from document ibrary i.e.
    If document ibrary = doclib then use as:

    queryOption.InnerXml =
    <Folder>doclib/folder/sub_folder/</Folder>

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>