Using SharePoint’s SPView Class and CAML as a Query Language

Using SharePoint’s SPView Class and CAML as a Query Language

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 feature?and one that seems to be far less documented?is 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 tag (that you must eventually close with ).

   String query = "";

Next, specify the field name (Column) that you would like to sort by.

   query += "";

By default SharePoint performs the sort in ascending order. To specify a descending order, add the following attribute:

   query += "";
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 += "";

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 += "";

If you have multiple conditions, you can choose from a group of conditional statements that CAML provides, including the basic: and .

   query += "";

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 to retrieve items that satisfy all the specified criteria.

Next, you specify operators, which include such possibilities as , and for strings, (greater than), and (less than) for numeric data, and (equals) for both.

   query += "";

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 += "";

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 +=  "GetMe!";

After completing the conditions, remember to close the Value and operator tags.

   query += "";

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 += "";                          // Condtion   query += "";                    // Operator   query += "";  // Field Name   query += "a";      // Value   query += "";           // Close tags

You’d repeat the preceding code for the letter ‘e’:

   query += "";                    // Operator   query += "";  // Field Name   query += "e";      // Value   query += "";           // Close tags

Now close the nested conditional statement:

   query += "";

To finish the “Filter” part of the query, you have to close any open conditional statements and the Where tag.

   query += "";

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:///sites//Lists/      /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.


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist