Geeks With Blogs
Reidar Husmo SharePoint from the trenches

I've recently had to help a couple of splinq-challenged colleagues with some caml queries.

Here are some of my favourite ways to make caml edible.

  • Use '!
    Too many developers seem ignorant of the fact that xml works just as well with single apostrophes as with double. This is, of course, also true for other things, like html.
  • Use @ and multiline
  • Use string.Format
  • Validate the query using a simple webpart or, much better, powershell
  • Don't use third-party clever stuff

I'm not sarcastic when I say "clever," I'm really impressed with what some people, like John Holliday, have done. But I have two major problems. You include a dependency to a dll which is outside your control, which can lead to all kinds of interesting deployment and upgrade problems. But more importantly, these additions seldom cover 100% of the functionality, and you may therefore think that something is impossible just because the addition doesn't support it.

So, examples.

var query = new SPQuery();

query.Query = "<Where><Eq><FieldRef Name=\"Severity\" /><Value Type=\"Choice\">Error</Value></Eq></Where>";


query.Query = @"



      <FieldRef Name='Severity' />

      <Value Type='Choice'>Error</Value>



Which, IMHO, is more readable.

Another example using string.Format:

            query.Query = string.Format(@"<Where>


                                                <FieldRef Name='Title'/><Value Type='Text'>{0}</Value>


                                        </Where>", filename); // GAH! sorry about tabification (blog editor)

And how do you test it in PowerShell?

$filename = "test"

$query = New-Object Microsoft.SharePoint.SPQuery

$query.Query = @"



            <FieldRef Name='Title'/>

            <Value Type='Text'>$($filename)</Value>




# See? Powershell does multiline strings, too!

# yes, Powershell has string.Format - but in Powershell I prefer using the built-in mechanism

$items = $list.GetItems($query)

foreach ($item in $items)


    Write-Host -NoNewline $item.DisplayName



Beautiful, just beautiful. Well, the PowerShell bit, not the CAML bit. Splinq is, obviously, much prettier.

Posted on Wednesday, March 28, 2012 10:40 AM SharePoint 2010 , Powershell | Back to top

Comments on this post: CAML queries for humans

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Norgean | Powered by: