Using SharePoint's SPView Class and CAML as a Query Language
Learn how to use Microsoft's XML-based Collaborative Application Markup Language (CAML) as a query language, letting you find and display SharePoint items dynamically.
by
Michael Peterson

f you've been working to customize SharePoint, you've probably at least heard the term "CAML," which stands for Collaborative Application Markup Language. CAML is the XML-based language that Microsoft uses to build and customize SharePoint sites. Many of SharePoint's
.site definition XML files are written in CAML. However, CAML is capable of more than site definitions; another CAML featureand one that seems to be far less documentedis that you can use it as a query language. CAML queries allow you to dynamically find and display SharePoint items based on various criteria. If you've ever created a List View you may not have been aware of what was really going on.
 | |
| Figure 1. Creating a List View: When you create a List View, SharePoint automatically creates a CAML query. |
When you specify a "Sort" or "Filter" during the List View creation process, you are creating the value for the SPView object's
Query value (see
Figure 1). The SPView class is the programmatic representation of a List View. You can view the generated List View query programmatically by simply exposing the string return value from the
SPView.Query property, as you'll see below. But you aren't limited to creating CAML queries through dialog interaction. This article discusses how you can create such CAML queries programmatically.
CAML Query Statements
There are two main parts to a CAML query statement: The first is straightforward but the second can become a little more complicated. From now on I will refer to them as the "Sort" and "Filter" parts.
For the following example create a List View called "Search," leaving all the default values. The newly created SPView object is accessible from the SPWeb object.
SPWeb web = SPControl.GetContextWeb(this.Context);
SPView view = web.Lists["List Name"].Views["Search"];
You can get or set the view's query string through its
Query property:
// Get
string query = view.Query;
// Set
view.Query = query;
view.Update();
| Author's Note: You must call update for the changes to take effect. |
Building a CAML Query
Now let's get into the actual building of the query string. The first but optional part of the string is the "Sort." Here you can specify which columns you would like the data sorted by and specify an ascending or descending sort order.
If you are going to include any type of sorting the query string needs to start with an <OrderBy> tag (that you must eventually close with </OrderBy>).
String query = "<OrderBy>";
Next, specify the field name (Column) that you would like to sort by.
query += "<FieldRef Name=\"Cloumn1\">";
By default SharePoint performs the sort in ascending order. To specify a descending order, add the following attribute:
query += "<FieldRef Name=\"Cloumn2\"
Ascending=\"FALSE\"/>";
| Author's Note: Spaces are not allowed in column names! You must replace spaces with their hex representation: _x0020_. For example, you'd enter a column named "Column 1" as Column_x0020_1. |
You can include as many column entries as needed, using the same syntax shown above. When you're done, remember to close the "Sort" part of the query.
query += "</OrderBy>";
Now comes the "Filter" part, which can get a little tricky. That part begins with a
tag that is much like the
WHERE clause in a SQL
SELECT statement.
query += "<Where>";
If you have multiple conditions, you can choose from a group of conditional statements that CAML provides, including the basic:
<And> and
<Or>.
query += "<And>";
Of course, you can omit this part for single-condition statements, using only a single statement inside your
tag. For this article I'll use
<And> to retrieve items that satisfy all the specified criteria.
Next, you specify operators, which include such possibilities as
<Contains>, and
<BeginsWith> for strings,
<Gt> (greater than), and
<Lt> (less than) for numeric data, and
<Eq> (equals) for both.
query += "<Eq>";
Next specify the field name much like you did for the "Sort" part of the query. Remember that you can't include spaces in field names!
query += "<FieldRef Name=\"Column1\"/>";
After that, specify the value type and the value that the item must satisfy. The following example searches for items where the value in the
Column1 field equals
GetMe!.
query += "<Value Type=\"String\">GetMe!";
After completing the conditions, remember to close the
Value and operator tags.
query += "</Value></Eq>";
Building a CAML Query (continued)
You can nest conditional statements. For instance to retrieve items where Column2 contains an "a" or "e" and Column 1 contains GetMe! you could add the following:
query += "<Or>"; // Condtion
query += "<Contains>"; // Operator
query += "<FieldRef Name=\"Column2\"/>"; // Field Name
query += "<Value Type=\"String\">a"; // Value
query += "</Value></Contains>"; // Close tags
You'd repeat the preceding code for the letter 'e':
query += "<Contains>"; // Operator
query += "<FieldRef Name=\"Column2\"/>"; // Field Name
query += "<Value Type=\"String\">e"; // Value
query += "</Value></Contains>"; // Close tags
Now close the nested conditional statement:
query += "</Or>";
To finish the "Filter" part of the query, you have to close any open conditional statements and the
Where tag.
query += "</And></Where>";
You can see a complete example that uses the methods you've seen here to build dynamic query strings in the
downloadable sample code.
You've just built a query statement that will sort Column1 in ascending order and then by Column2 in descending order, and will show only those rows where Column1 equals
GetMe! and Column2 contains an "a" or "e."
You can now assign the completed string to the SPView's
Query property and trigger an update so the changes will take effect.
view.Query = query;
view.Update();
Edit SPViews Dyamically
The
downloadable code example contains a Web Part that allows users to dynamically edit the
SPView.Query property of a view called "Search." The Web Part uses the same method shown in this article to build the query string. To use the Web Part, attach it to the list's Search view page by appending
?ToolPaneView=2 to the end of the URL, for example:
 | |
| Figure 2. Search Example: This sample Web Part lets you experiment with CAML by changing search parameters interactively, building CAML queries as described in the article. |
http://<servername>/sites/<sitename>/Lists/
<List Name>/Search.aspx?ToolPaneView=2
You must also specify the list name in the Web Part Properties. If installed correctly, it should appear as shown in
Figure 2.
Using CAML as a query language has many different applications and allows you to display your data in many different ways. It can be used with various functions provided by the SharePoint object model and can prove to be an invaluable resource if you find yourself working with lists, items, and views.
Michael Peterson currently works as a SharePoint developer for Susquehanna Technologies. He specializes in custom functionality and collaborative applications.