Using XPath

Using XPath

SelectItemsUsingXpath() Method

  • Supports using XPath to retrieve an item array from a Sitecore database
  • Does not support all of the constructs normally supported with XPath in Sitecore, such as //*

Controls featured in this example:

  • Sitecore Web Control

Classes featured in this example:

  • Sitecore.Collections.ItemList
  • Sitecore.Context
  • Sitecore.Data.Database
  • Sitecore.Data.Items.Item
  • Sitecore.StringUtil
  • System.Linq

Using XPath C# Web Control Code

Sitecore.Data.Items.Item item = this.GetItem();
if (item == null) return;

string xpath = "/*/item[@key='content']/item[@key='home']/item[@key='developers']/item[@key='caching']/descendant::item";

Sitecore.Data.Database db = Sitecore.Context.Database; 
Sitecore.Collections.ItemList descendants = db.SelectItemsUsingXPath(xpath);
if (descendants == null) return;
var sortedList = (from entry in descendants orderby entry.Fields["title"].Value ascending select entry);

output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-weight:bold; width:100%; clear:both");
output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.Div);
output.Write("C# Web Control Real-time Output");
output.RenderEndTag();

output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-size:x-small; width:100%; clear:both");
output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.Div);
output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-weight:bold");
output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.P);
string displayName = Sitecore.StringUtil.GetString(item.DisplayName, item.Name);
//using : for colon and   for space
output.Write("{0}: {1}", "Item", displayName);
output.RenderEndTag(); //P

output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.P);
output.Write("{0}", "Displaying Ten Filtered Descendants");
output.RenderEndTag(); //P

int i = 0;
foreach (Sitecore.Data.Items.Item descendant in sortedList)
{
    i++;
    output.Write("{0}", descendant.DisplayName + "<br/>");
    //only display first ten items
    if (i >= 10) break;
}

output.RenderEndTag(); //Div


Using XPath C# Web Control Output

Displaying Ten Filtered Descendants

/sitecore/content/Home/Developers/Caching/CacheStates
/sitecore/content/Home/Developers/Caching/CacheStates/BrowserCaching
/sitecore/content/Home/Developers/Caching/CacheStates/CacheManager
/sitecore/content/Home/Developers/Caching/CacheStates/CacheSettings
/sitecore/content/Home/Developers/Caching/CacheStates/CacheStatus
/sitecore/content/Home/Developers/Caching/CacheStates/ClearAllCaches
/sitecore/content/Home/Developers/Caching/CacheStates/DataProviderCaching
/sitecore/content/Home/Developers/Caching/CacheStates/LoadFactorSettings
/sitecore/content/Home/Developers/Caching/CacheStates/MediaCacheSettings
/sitecore/content/Home/Developers/Caching/DatabaseCaches