Friday, July 6, 2012

Parsing Managed Metadata fields in lists

Ok, here's an easy one (and short one for those of you short on patience). With the advent of the Managed Metadata Service, we've all come to know and love Groups, Term Sets and, naturally, Terms. So the question becomes, what is an effective way of parsing through a multi-value enabled Managed Metadata field to capture their text values. Easy, it's just a matter of parsing through a TaxonomyFieldValueCollection object. Here goes nothing...

First thing you have to remember is to apply a using directive to qualify use of the SharePoint Taxonomy class. I can't tell you enough how nice it is come across a post that reminds us what classes are leveraged for a given solution.

    using Microsoft.SharePoint.Taxonomy;

So let's say we have a ListItem declared as "_MyListItem," and we want to capture the text values saved in a Managed Metadata field called "MySpecialTerms" in a List object called "_MyListOfTerms." Here's how you do it:

List<string> _MyListOfTerms = new List<string>();

foreach (TaxonomyFieldValue aSingleTermValue in 
    (TaxonomyFieldValueCollection)_MyListItem["MySpecialTerms"])
{
   _MyListOfTerms.Add(aSingleTermValue.Label);
}

VoilĂ !

Happy Coding.