LinkedIn

Tuesday, 7 April 2009

Building queries for working with Folders

Credit to:
http://sharepointmagazine.net/technical/development/writing-caml-queries-for-retrieving-list-items-from-a-sharepoint-list for this info.


------


A first variant I will explain is how you can work with folders and sub folders. A folder is a special list item on a list or document library. If you execute a standard CAML query you will end up with list items from the root folder.


If you want to query all folders and sub folders of a list or document library, you have to define extra query options. If you are working with the object model you have to set the ViewAttributes property of the SPQuery object as follows:


qry.ViewAttributes = "Scope='Recursive'";


If you work with GetListItems method of the Lists.asmx SharePoint web service, you have to define an extra node with the QueryOptions element:


XmlNode queryOptionsNode = camlDocument.CreateElement("QueryOptions");


queryOptionsNode.InnerXml = "";

If you want to query a specific sub folder using the SPQuery object, you have to set the Folder property:

qry.Folder = list.ParentWeb.GetFolder("Folders DocLib/2008");

When working with the web services you have to do the following:

XmlNode queryOptionsNode = camlDocument.CreateElement("QueryOptions");

queryOptionsNode.InnerXml = "
Folders DocLib/2008";

-----

So my CAML looked like this:
<Query>
<Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='Text'>testdoc.docx</Value></Eq></Where>
</Query>
<ViewFields>
<FieldRef Name='Title' />
</ViewFields>
<QueryOptions>
<Folder>Documents/[002643][Test%20project%20for%20Adam]/[ACPC][126573][1][writeFileAndXmlTest2]</Folder>
<OptimizeFor>FolderUrls</OptimizeFor>
</QueryOptions>

RuSs