Access a branch of items
You can access all of the items in a branch by using a recursive method and the Sitecore.Data.Items.Item.Children property. For example, to process the /Sitecore/Content/Home item in the Master database, and each descendant of that item:
Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");
Sitecore.Data.Items.Item home = master.GetItem("/sitecore/content/home");
ProcessRecursively(home);
...
private void ProcessRecursively(Sitecore.Data.Items.Item item)
{
foreach(Sitecore.Data.Items.Item child in item.Children)
{
// Process child item
ProcessRecursively(child);
}
}If the recursive method passes its argument to itself, then that method implements an infinite loop.
To avoid processing the root item in the branch, move the processing logic within the loop into the recursive method that iterates the children, and in that logic, process the child item instead of the item passed to the recursive method. For example, to process only the descendants of the /Sitecore/Content/Home item in the Master database:
Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");
Sitecore.Data.Items.Item home = master.GetItem("/sitecore/content/home");
ProcessRecursively(home);
...
private void ProcessRecursively(Sitecore.Data.Items.Item item)
{
foreach(Sitecore.Data.Items.Item child in item.Children)
{
// Process child item
ProcessRecursively(child);
}
}You can also use Sitecore query to access an entire branch using either the descendant or descendant-or-self axis.