Clean your XPath

March 01, 2011
Tags: SDN, Sitecore, XPath

While developing with Sitecore you'll probably end up using XPath query to return some results. Since a lot of people will be requiring you to create content items with dashes in the name, for SEO purposes, you're going to need to escape the dashes with "#" (pound) signs as detailed in this SDN Sitecore Query Syntax article. This means you'll need a method to clean your XPath queries. Having done this a few times and integrated mine with other developers versions, here's what I've come up with:

public static class StringExtensions {	public static string CleanXPath(this string s) {		string scQuery = s;		//loop through each match and replace it in the query with the escaped pattern		char[] splitArr = { '/' };		string[] strArr = scQuery.Split(splitArr);		//search for {6E729CE5-558A-4851-AA30-4BB019E5F9DB}		string re1 = ".*?";	// Non-greedy match on filler		string re2 = "([A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12})";	// GUID		Regex r = new Regex(re1 + re2, RegexOptions.IgnoreCase | RegexOptions.Singleline);		for (int z = 0; z <= strArr.Length - 1; z++) {			Match m = r.Match(strArr[z]);			//if it contains a dash and it's not a guid			if (strArr[z].Contains("-") && !m.Success) {				strArr[z] = "#" + strArr[z] + "#";			}		}		scQuery = string.Join("/", strArr);		return scQuery;	}}

Now let's wrap that all up into a single method for you to call using the Linq ToList extension.

public static class StringExtensions {	public static List<Item> RunXPath(this string s, Sitecore.Data.Database db) {		return db.SelectItems(s.CleanXPath()).ToList();	}}

And voila, you've got yourself a couple handy little extension methods that let you get to the work of Sitecore without the hassle.