Helper Method to Extract Taxonomy Field Column Value From SPListItem

Introduction

This article talks about how to extract a term label from the Managed Metadata column. The list that includes a Managed Metadata column or Taxonomy Field stores the data in the following format.

Column Name Column Type Simple Value Data Format
Location Taxonomy Field 2; # Chennai WSS Id; Name of Team
Location TaxHTField0 Note Chennai | c61d9028-824f-446e-9389-eb9515813a42 Name of Term | GUID of Term

The WSS identifier is a 32-bit integer that uniquely identifies list's list item containing the taxonomy field. This property behaves similarly to the LookupId property and is used as the lookup identifier on the TaxonomyHiddenList list.

Practical Scenario

Please find the following is the Managed Metadata column named "Location” added in Test List in SharePoint Site.

manage metadata

Now I have added a new list item with Term Value as Chennai for Location.

test data

Please have a look at the following helper method that will extract only a Term Label value from the Managed Metadata column.

  1.   /// <summary>    
  2.   /// method to get value from Taxonomy field column from splistItem    
  3.   /// </summary>    
  4.   /// <param name="spListItem">object of splistItem</param>    
  5.   /// <param name="taxonomyField">taxonomy field column name</param>    
  6.   /// <returns>returns a string of Term label</returns>    
  7.   public static string GetTaxonomyFieldValue(SPListItem spListItem, string taxonomyField)    
  8.   {    
  9.       string fieldValue = string.Empty;    
  10.       try    
  11.       {    
  12.           TaxonomyFieldValueCollection spTaxonomyFiledValueCollection = spListItem    
  13.           [taxonomyField] as TaxonomyFieldValueCollection;    
  14.     
  15.           foreach (var field in spTaxonomyFiledValueCollection)    
  16.           {    
  17.               fieldValue = field.Label;    
  18.           }    
  19.       }    
  20.       catch (Exception exception)    
  21.       {    
  22.           //Log an exception    
  23.           throw;    
  24.       }    
  25.       return fieldValue;    
  26.  }    
Here you need to pass the parameters as an object of SharePoint List Item and Managed Metadata column internal name as shown in the following example.

GetTaxonomyFieldValue(oSPListItem,"Location")

This will return a term label as "Chennai" and if you need a Term GUID then replace the field.Label property with the field.Guid.

Happy SharePointing!