I’ve not found any built-in method to get a specific Term in the taxonomy hierarchy by specifying its path. I mean the name of the parent terms from the root TermSet and the name of the term itself, like “parent of the parent term name/parent term name/term name”. Terms having the same name may exist at multiple levels or branches of the taxonomy, so the name of the term is not necessarily unique within a TermSet, one can not use that to look up the exact Term.
So I’ve created an extension method that does just what I need, here is the code:
- public static class Helper
- {
- public static Term GetTermByPath(this TermSet termSet, String path)
- {
- Term result = null;
- String[] pathElements = path.Split(new Char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
- int depth = 0;
- result = termSet.Terms[pathElements[depth]];
- while (depth < pathElements.Length-1)
- {
- depth++;
- result = result.Terms[pathElements[depth]];
- }
- return result;
- }
- }
In the following code we assume a term set hierarchy that was imported from the sample import CSV as I’ve discussed in a former post.
- TaxonomySession session = new TaxonomySession(site);
- TermStore termStore = session.TermStores["Managed Metadata Service"]; // replace it to fit your configuration
- Group group = termStore.Groups["GroupName"]; // replace it to fit your configuration
- TermSet termSet = group.TermSets["Political Geography"];
- Term term = termSet.GetTermByPath("Continent/Political Entity/Country/Province or State/County or Region/City/District");
As usually the codes above are only for illustration purposes. If you would like to use them in a production code, you should add some kind of exception handling to them.
And please, let me know if you find this method in the standard API!
Tags: SP 2010, Taxonomies
February 11, 2010 at 16:24 |
[...] the GetTermByPath method I used to get the value of the AnchorId property see my former post. Anchor is a term that refers to the Term that is the starting point of the “navigation” within [...]
December 8, 2010 at 16:06 |
Hi,
I’m exporting user profile properties to xml and would like to export taxonomy if the property has a termset. I can get the termset like this:
property.Termset.Name.
How do I get parent group or groups of this termset?
Thanks.
December 21, 2010 at 22:21 |
Hi Joe,
See the definition of the TermSet class. It contains a property called Group that returns the parent group for the term set.
Peter