How does one get all child terms of a SharePoint term in C#?

Tom Macdonald picture Tom Macdonald · Mar 10, 2011 · Viewed 23.4k times · Source

I am writing a webpart for SharePoint 2010 that recuperates the latest page of a certain (custom) type, according to publishing date. It only takes into account pages tagged with a specified term. I would like it to be able to also do so with pages that are tagged with terms which are children of the selected terms.

If I have a term tree like so:

  • England
    • Kent
      • Dover
      • Canterbury
    • Surrey
      • Croydon
      • Crawley

then by selecting Kent, I want my webpart to show the latest page tagged with Kent, Dover, or Canterbury.

Is this possible in C# ?

Thanks for your time.

Answer

Nat picture Nat · Mar 11, 2011

The function you are looking for is Term.GetTerms

You will need to get a TaxonomyValue from your field

Then you have to get the current TaxonomySession, then use the TaxonomySession to get the Term used in the field. From that term you can use the Parent field to get the parent Term. Here is some rough code to show you the objects used.

         TaxonomyFieldValue v = null; // Notsurehowtodothisbit();
        TaxonomySession session = new TaxonomySession(site);
        if (session.TermStores != null && session.TermStores.Count > 0)
        {

            TermStore termStore = session.TermStores[0];
            Term t = termStore.GetTerm(v.TermGuid);
            Term parentTerm = t.Parent;   
            TermCollection childTerms = t.GetTerms();
        }

Once you have the tree, you may be able to use a caml query to generate a SPList.GetList query that brings back anything tagged that way.

I have not done an experiment in this regard... But Bart-Jan Hoeijmakers has

    private SPListItemCollection GetItemsByTerm(Term term, SPList list)
    {
        // init some vars    SPListItemCollection items = null;    
        SPSite site = SPContext.Current.Site;     // set up the TaxonomySession    
        TaxonomySession session = new TaxonomySession(site);
        // get the default termstore    TermStore termStore = session.TermStores[0];   
        // If no wssid is found, the term is not used yet in the sitecollection, so no items exist using the term   
        int[] wssIds = TaxonomyField.GetWssIdsOfTerm(SPContext.Current.Site, termStore.Id, term.TermSet.Id, term.Id, false, 1);
        if (wssIds.Length > 0)
        {
            // a TaxonomyField is a lookupfield. Constructing the SPQuery       
            SPQuery query = new SPQuery();
            query.Query = String.Format("<Where><Eq><FieldRef Name='MyTaxonomyField' LookupId='TRUE' /><Value Type='Lookup'>{0}</Value></Eq></Where>", wssIds[0]);
            items = list.GetItems(query);
        }
        return items;
    }