How to write a CAML query to find out a list of items with ID
Hi,
Few days ago I came around a problem where I have to query a SharePoint list for a bunch of items and I only have the ID for those. The ID field is a counter. I am using the WebService.GetListItems method for the query.
By googleing I came to know that I have to write the query in the following manner to fetch 1 item:
<Where>
<Eq>
<FieldRef Name=’ID’/>
<Value Type=’Counter’>” + _slideid + “</Value>
</Eq>
</Where>
Where the slide id is one of the IDs of from the slide list.
The query worked well but I wanted to extend it for n number of items. i.e. If I have a Slide ID array, I want to get the Items in one query. Here is the code snippet that does the trick:
XmlNodeList GetFilteredNodesFromSharepointBySlideID(string _tmpListName, string _tmpViewName, string[] _slideid)
{
XmlNodeList _tmplNodeLists = null;
try
{
XmlDocument doc = new XmlDocument();
XmlNode query = doc.CreateNode(XmlNodeType.Element, “Query”, “”);
String _query = “<Where>”;
String _innerQ = “”;
string _tempQ = “”;
for (int i = 0; i < _slideid.Length; i++)
{
_tempQ += “<Eq><FieldRef Name=’ID’/><Value Type=’Counter’>” + _slideid[i] + “</Value></Eq>”;
if (i >= 1)
{
_innerQ = “<Or>” + _tempQ + “</Or>”;
_tempQ = _innerQ;
}
}
_query += _tempQ + “</Where>”;
query.InnerXml = _query;
XmlNode templistItems =
MyWebService.GetListItems(_tmpListName, _tmpViewName, query,
null, null, null, null); //MyWebService is the Configured Web Service
doc.LoadXml(templistItems.OuterXml);
_tmplNodeLists = doc.GetElementsByTagName(“z:row”); // Now you can return the node list as XMLNodes.
}
catch (Exception _e)
{
throw _e;
}
return _tmplNodeLists;
}
I tried to input the slide ids 19,20,21,22,23 and the output of the CAML query is like below:
<Where>
<Or>
<Or>
<Or>
<Or>
<Eq>
<FieldRef Name=”ID” />
<Value Type=”Counter”>19</Value>
</Eq>
<Eq>
<FieldRef Name=”ID” />
<Value Type=”Counter”>20</Value>
</Eq>
</Or>
<Eq>
<FieldRef Name=”ID” />
<Value Type=”Counter”>21</Value>
</Eq>
</Or>
<Eq>
<FieldRef Name=”ID” />
<Value Type=”Counter”>22</Value>
</Eq>
</Or>
<Eq>
<FieldRef Name=”ID” />
<Value Type=”Counter”>23</Value>
</Eq>
</Or>
</Where>
I hope you can understand the utility of the script now. You can now extend it as you like.
Happy coding!
