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.
query:/sitecore/content/some/path-with-dash/becomes
query:/sitecore/content/some/#path-with-dash#/becomes
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.
https://github.com/istern/RenderingsDatasources
Saved like a favorite, cool web page!
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.
Thank You. This saved my time. 🙂