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; }
}