Get top level parent of Term in SharePoint Taxonomy using C#

While working with SharePoint taxonomy sometimes we come across the problem where we want to get the top level parent of the given TermId. So here i am sharing the way of getting the top level parent term using given Term Id using c# code.

For the implementation of the code you will need to include Microsoft.SharePoint.Taxonomy library.

The below given code you can keep on any event action when you want to get the parent term.

HttpContext oldContext = HttpContext.Current;
HttpContext.Current = null;
string TermId = "Your Term Id"
Term ParentTerms = null;
using (SPSite site = new SPSite("Your site URL"))
TaxonomySession taxonomySession = new TaxonomySession(site);
TermStore termStore = taxonomySession.TermStores["Your Managed MeataData Service Name"];
Group group = termStore.Groups["Your Termstore Group Name"];
TermSet sectionTermset = group.TermSets["Your Termset Name"];
ParentTerms = getParentTerm(sectionTermset, TermId);

/* “ParentTerms” is the object of your term, so using this you can get the details of the term like name, Id etc
catch (Exception ex)
// your catch code

Here the method “getParentTerm()” is called recursively to get the top level parent. The definition for the method is as below:-

public Term getParentTerm(TermSet termSet, string termGuid)
Term parentSectionTerm = null;
Term newParentSectionTerm = null;
parentSectionTerm = termSet.GetTerm(new Guid(termGuid));
var isTopLevelParent = parentSectionTerm.IsRoot;
if (!isTopLevelParent)
newParentSectionTerm = parentSectionTerm.Parent;
getParentTerm(termSet, Convert.ToString(newParentSectionTerm.Id));
newParentSectionTerm = parentSectionTerm;
return newParentSectionTerm;

Here “IsRoot” is the property of the term which returns true/false, if the term does not have any parent then it will return ‘true’, and if the term has the parent then it will return ‘false’.

I hope this article will help you to get rid of your problem for getting top level parent of the Term

Leave a Reply

Your email address will not be published. Required fields are marked *