Monday, October 4, 2010

Retrieving Taxonomies Progrmatically

I recently made a quick google search on how to retrieve taxonomies programatically, and I could not find anything, so I thought I would blog about how to do it.
Get from it what you can.

SPSite thisSite = SPContext.Current.Site;
TaxonomySession session = new TaxonomySession(thisSite);
foreach (TermStore tStore in session.TermStores)
{
    Console.WriteLine("Term Store:" + tStore.Name);
    foreach (Group tGroup in tStore.Groups)
    {
        Console.WriteLine("Group:" + tGroup.Name);
        foreach (TermSet tSet in tGroup.TermSets)
        {
            Console.WriteLine("Term Set:" + tSet.Name);
            foreach(Term term in tSet.Terms)
            {
                Console.WriteLine("Term:" + term.Name);
            }
        }
    }
}

Or you can use this way

TaxonomySession session = new TaxonomySession(siteCollection);
TermStore termStore = session.TermStores[tagsField.SspId];
TermSet termSet = termStore.GetTermSet(tagsField.TermSetId);
myTerm = termSet.Terms[myTermName];

In this scenario tagsField was a taxonomy field that I am trying to update and myTermName is the term name I am trying to get (let me know if you get confused).

No comments:

Post a Comment