The Light
The Light

Reputation: 27011

How to Create a CAML Query to Retrieve a List Item?

XmlElement camlQuery = Build(); // how to implement this?

I have a SharePoint list called Authors which has an genericId field.

How to write a CAML query for something like below:

Select Name from Authors where genericId = 1

Then the camlQuery will be passed to the ListItems sharepoint web service:

http://msdn.microsoft.com/en-us/library/lists.lists.getlistitems(v=office.12).aspx

What I have tried is to create an xml element as below:

 XmlDocument xmlDoc = new XmlDocument();

 XmlElement camlQuery = xmlDoc.CreateElement("Query");

 camlQuery.InnerXml = "<Where><Lt><FieldRef Name='genericId'/><Value Type='Integer'>9</Value></Lt></Where>";

Then this is passed to the GetListItems() service (not sure what's the meaning of Lt or Gt, etc?).

But it throws an exception:

Exception of type 'Microsoft.SharePoint.SoapServer.SoapServerException' was thrown.

Many thanks,

Upvotes: 1

Views: 5320

Answers (3)

murat
murat

Reputation: 21

Check this approach very easy to create caml query even run the query: Link

cawl_QueryBuilder cawl = new cawl_QueryBuilder;
cawl.Where("FirstName","=","Mike");
cawl.Where("Status","!=","Passive");
cawl.Get("Users");

Gridview1.Datasource= cawl.ListItemCollection().GetDataTable();
Gridview1.Databind();

Upvotes: 0

user4531
user4531

Reputation: 2565

You can create CAML Queries with the
U2U CAML Query Builder for SharePoint 2003 and SharePoint 2007
,
the U2U CAML Query Builder Feature -
OR you could use LINQ to SharePoint as an alternative (if you've got SharePoint 2010)

Upvotes: 0

Maks Matsveyeu
Maks Matsveyeu

Reputation: 866

I think it would be nice to teach you how to write it "yourself" rather then just giving you the right answer.

I assume you have a local farm. Create a view in a sharepoint list and make it return the right result by using filters. Then download this tool http://spm.codeplex.com/ and navigate to you view. Then copy and paste the CAML OF A VIEW into your code. That is it.

P.S. LT stands for less than, GT stands for greater than. You will need Eq (equal) in your case.

Good luck.

Upvotes: 1

Related Questions