Handle "&" in CAML query in MOSS / SharePoint 2010

By Jatin Prajapati

In this FAQ we will see how to handle the "&" in CAML query in MOSS / SharePoint 2010.

While writing custom code or developing custom web part for SharePoint 2010 or MOSS 2007, frequently we have to write CAML query to get list or document library items. In some cases we have "&" in the value based on which we are trying to filter and get data. As, the CAML is the specialised and formated XML, it will break when it encounters "&" in query. So, for example, if we write our query like

<Where><Contains><FieldRef Name=\"Title\" /><Value Type=\"Text\">Legal & Compliance</Value></Contains></Where>

then, we will never get the items from the list or document library. So, to resolve this problem we have to use the traditonal XML way for handling the special characters and it is "<![CDATA[]]>". So, our query will be

<Where><Contains><FieldRef Name=\"Title\" /><Value Type=\"Text\"><![CDATA[Legal & Compliance]]></Value></Contains></Where>

So, when we use the above query, we have list items as the result of our query.

See the below working example.

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.Publishing.WebControls;
using System.Data;
using System.Web.UI.HtmlControls;
using System.Text;

namespace Investis.Hiscox.Webparts.TestWebPart
{
    [ToolboxItemAttribute(false)]
    public class TestWebPart : WebPart
    {
        // Visual Studio might automatically update this path when you change the Visual Web Part project item.
        private const string _ascxPath = @"~/_CONTROLTEMPLATES/Investis.Hiscox.Webparts/TestWebPart/TestWebPartUserControl.ascx";

        protected override void CreateChildControls()
        {
            this.GetItems("Legal & Compliance");
        }

         private void GetItems(string filterValue)
        {
            SPQuery query = BuildQuery(filterValue);
            SPList lst = SPContext.Current.Web.Lists["Contents"];
            SPListItemCollection items = lst.GetItems(query);
           StringBuilder sb = new StringBuilder();
            foreach (SPListItem item in items)
             {
                 sb.AppendFormat("{0}<br/>", item.Title);
            }
            this.Controls.Add(new LiteralControl(sb.ToString()));
        }

        private SPQuery BuildQuery(string value)
        {
            SPQuery query = new SPQuery();
             query.Query = "<Where><Contains><FieldRef Name=\"Title\" /><Value Type=\"Text\"><![CDATA[" + value + "]]></Value></Contains></Where>";
            return query;
        }
     }
}

Handle "&" in CAML query in MOSS / SharePoint 2010  (1266 Views)