Assumptions
Assuming you have a link to Sitecore.Data.Items.Item (called item ), and you would like to find the ancestor with the given Sitecore.Data.ID (called id ), there are several ways to access the ancestor.
Using Linq
In a typical Sitecore setup without any custom libs, I would normally use the Linq bit to avoid coding problems in XPath.
ancestor = item .Axes .GetAncestors() .FirstOrDefault(ancestor => ancestor.TemplateID == id);
Using Closest
I use a special sitecore development framework that includes a wide range of extension methods and personalized element creation. To avoid the overhead of accessing all ancestors before filtering, I would use the Closest extension method:
public static Item Closest(this Item source, Func<Item, bool> test) { Item cur; for (cur = source; cur != null; cur = cur.Parent) if (test(cur)) break; return cur; }
Access to the ancestor will be as follows:
ancestor = item .Closest(ancestor => ancestor.TemplateID == id);
(Actually, I usually use code that looks)
ancestor = (ITemplateNameItem) item.Closest(Is.Type<ITemplateNameItem>);
Using XPath
I usually avoid XPath and use it only as a last resort, because it often makes the code harder to read, introduces encoding problems like the one you encountered in this question, and has a hard limit on the number of elements that can be returned.
However, Sitecore has many tools for searching with XPath, and in some cases it makes it easier.
Trick to fix paths of elements containing spaces: Do not use element paths.
Instead, you can safely use the element identifier without the need for more context, because it is an absolute reference to the element. It also guarantees the execution of a specific format.
var query = string.Format( "//{0}/ancestor::*[@@templateid='{1}']", item.ID.ToString(), id.ToString()); ancestor = item .Database .SelectSingleItem(query);
Using Sitecore.Data.Query.Query
As I mentioned earlier, Sitecore has many search tools in XPath. One of these tools is Sitecore.Data.Query.Query . The SelectItems and SelectSingleItem have additional optional parameters, one of which is Sitecore.Data.Items.Item as contextNode .
Passing an element as the second parameter uses this element as the context for the XPath request.
var query = string.Format( "./ancestor::*[@@templateid='{0}']", id.ToString()); ancestor = Sitecore .Data .Query .Query .SelectSingleItem(query, item);