Home > C#, Sitecore > Escaping dashes/“-” in Sitecore Queries. Datasource query Update

Escaping dashes/“-” in Sitecore Queries. Datasource query Update

This is actually more an update to the post Query in Datasource location I wrote some while ago. As I was working on a new solution I often saw an error with “unterminated literal string in Query”. In my case it was actually quite simple because an item name include a dash “-”, which is an illegal character  in a query, the solution is to escape the part of the the path that contains  the “-”.  you escape it by adding “#” around the word, see the example below. 



 The code to fix this is simple and Anders Laub wrote the version you see below.

private string EscapeItemNamesWithDashes(string queryPath)
  if (!queryPath.Contains("-"))
   return queryPath;

  var strArray = queryPath.Split(new char[] { '/' });
  for (int i = 0; i < strArray.Length; i++)
    if (strArray[i].IndexOf('-') > 0)
    strArray[i] = "#" + strArray[i] + "#";
  return string.Join("/", strArray);


The source code for using queries is also available on github , with the above enhancement.




Categories: C#, Sitecore Tags: , ,
  1. 19/11/2014 at 21:12

    Saved like a favorite, cool web page!

  2. Flemming Madsen
    13/01/2016 at 17:18

    This is not the case unfortunately when using the code API. When using a Query in ex. Database.SelectSingleItem(query) or Database.SelectItems(query), then if you escape an itemname with dash inside – then it simply returns no Items. It does not throw exception, but it returns no items. HOWEVER – in the case where the Query also contains ex. parent-or-self::* or decendants::* [@@templateID=’…’] or such syntax, then suddently the escape is needed and fully Works in the API. So the case is that it is not documented or logical when to use the escape and when not to. In FastQuery, escaping needs to be done in all cases where dash is in item name. But in Query it is not that simple.

  3. Nikki Punjabi
    27/08/2016 at 12:36

    Thank You. This saved my time. 🙂

  1. 02/11/2016 at 05:28
  2. 04/06/2017 at 17:55

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: