Home > Code > Traversing Taxonomy Terms from branch to leaf

Traversing Taxonomy Terms from branch to leaf

I had a need to show the path of terms, starting from a specific term and then showing the path to the final children,

This would involve traversing the structure as the depth is unknown, so I wrote this piece of code to accomplish this using the Client Components.

Please feel free to steal and improve (Only if you give back the improved code though!)

private IEnumerable<Path> Paths(bool includeRoot, Guid termId, string siteUrl)
{
var paths = new List<Path>();
Action<ClientContext, Term, String> traverse = null;

traverse = (context, term, path) =>
{
context.Load(term, t => t.Id, t => t.Name, t => t.Terms);
context.ExecuteQuery();

if (!(term.Id == termId && !includeRoot))
path += path == string.Empty ? term.Name : ” > {0}”.ToFormat(term.Name);

if (term.Terms.Count == 0)
{
paths.Add(new Path
{
TermId = term.Id,
PathText = path
});
}
else
{
foreach (var st in term.Terms)
{
traverse(context, st, path);
}
}
};

using (var context = new ClientContext(siteUrl))
{
var rootTerm = TaxonomySession.GetTaxonomySession(context).GetTerm(termId);

traverse(context, rootTerm, string.Empty);
}

return paths;
}

public class Path
{
public Guid TermId { get; set; }
public string PathText { get; set; }
}

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: