John Liu .NET

View Original

Style recommendation for writing CAML in C#

 

I came across some sample CAML code a while back, and have been following their way of defining CAML in C#

Today a colleague commented on my code and I thought, hey, I should write this down.

 

Use string.concat

 

var query = new SPQuery()
{
    Query = string.Concat(
                                "<Where>",
                                    "<Eq>",
                                    "<FieldRef Name='Parent' LookupId='true'/>",
                                    "<Value Type='Integer'>", id, "</Value>",
                                    "</Eq>",
                                "</Where>",
                                "<OrderBy>",
                                    "<FieldRef Name='DueDate' Ascending='TRUE' />",
                                    "<FieldRef Name=’Priority’ Ascending='TRUE' />",
                                "</OrderBy>")
};
var items = list.GetItems(query);

 

Benefits

 

  • You don't have to bury the CAML in one crazy line or block of text.
  • I can arbitrarily indent my XML elements and the code doesn't see it at all. 
  • You almost always need to insert some sort of variables in the middle of your CAML.  This way you don't have to rely on fancy string.format, or consider type casting.
  • You don't have to remember to add "..." + "..." at the end of every line. 
  • Don't like a chunk of XML?  You can easily line comment or region comment.

 

Try it out and see if this changes your life as it has for me.

(if you have been doing this for years and have blogged or seen this documented before, let me know where.)