Is Your Sitecore Query Not Working?

Friends, hope you are enjoying your Sitecore Journey! Let’s start our today’s journey. Scenario: What do you do when you find that your Sitecore query is NOT retuning any result even-though query is correct? The obvisous answer is you will go to Sitecore CE and fire that query using developer center, right? Yes – this is perfect troubleshooting step. I did the same, but was not able to understand that why Sitecore was giving error while executing that Sitecore query. I found no issue in syntax, then I tried same syntax by changing item name in query and it worked! This gave me some clue. It was now clear that there must be something with that particular item name and that made to write this post to help my Sitecore Journey riders!  Reason:  If your Sitecore query contains any reserve words (keywords) then it will throw an error. In my case, item name was containing word “and” which is Sitecore keyword.

Solution: Now you will find this post very simple because being a developer you know that every language gives some way to handle these escape characters (keywords). So you need to handle these escape characters in order to fix this issue. I took advantage of .NET extension method feature and created extension method which will take Sitecore item as input parameter and will return formatted item path after handling these Sitecore keywords.

 public static string GetFormattedItemPath(this Item itm)         {             string itemPath = itm.Paths.FullPath.ToLower();             if (itemPath.Contains(" and "))             {                 itemPath = itemPath.Replace(" and ", " #and# ");             }             else if (itemPath.Contains(" or "))             {                 itemPath = itemPath.Replace(" or ", " #or# ");             }             return itemPath;         } 

Above code handles only two keywords, but you can customize this code to handle entire list of Sitecore keywords as per your requirement. After writing above extension method, you simply need to call this method using your item object. For example:

Item currentItem = Sitecore.Context.Item; repeaterControl.DataSource = Sitecore.Context.Database.SelectItems(currentItem.GetFormattedItemPath() + "/Comments//*[@@templatename!='Folder']")

Below is a list of words that needs to be escaped when used in Sitecore query:

  •    and
  •    or
  •    child
  •    descendant
  •    div
  •    false
  •    following
  •    mod
  •    parent
  •    preceding
  •    self
  •    ancestor
  •    true
  •    xor

Have a Happy Sitecore Journey!

Leave a Reply