Programmatically Setting Taxonomy Field Values

Programmatically Setting Taxonomy Field Values

 var url = ConfigurationManager.AppSettings[“Url”].ToString();
var library = ConfigurationManager.AppSettings[“Library”].ToString();
// Reads XML, considering
 // (key => lookup field,value => taxonomy field)
 Dictionary<string, string> mappingFields = XMLHelper.ReadDictionaryXML(“MappingFields.xml”);
using (SPSite site = new SPSite(url))
using (SPWeb web = site.RootWeb)
   // Gets the list/library
 SPList list = web.Lists[library];
   foreach (SPListItem item in list.Items)
  // Iterates through all mapped fields
foreach (var mappedField in mappingFields)
 if (item.Fields.ContainsField(mappedField.Key))
// Allows updates without a trace
 web.Site.AllowUnsafeUpdates = true;
// Gets the lookup field instance
 var lookupValueList = (item[mappedField.Key] as SPFieldLookupValueCollection).ToList();
 // Gets the taxonomy field instance
TaxonomyField managedField = item[mappedField.Value] as TaxonomyField;
 // Gets the current taxonomy session
       TaxonomySession session = new TaxonomySession(web.Site, false);
 // Gets the term store (by SspId)
 var termStoreCol = session.TermStores[managedField.SspId];
 // Gets the terms of a specific term set (by TermSetId)
     var termCol = termStoreCol.GetTermSet(managedField.TermSetId).Terms;
var listTerms = new List<Term>();
 // Iterates through the lookup values
       foreach (var itemValue in lookupValueList)
    string value = itemValue.LookupValue;
// Gets the correspondent term for the each value
   // found in the lookup values list
                           var termToSet = termCol[value];
 // Sets the field value using the list of terms
        managedField.SetFieldValue(item, listTerms);
// Persists the item
// Denies further unsafe updates
 web.Site.AllowUnsafeUpdates = false;

About sharepointsriram

9+ Yrs of IT experience
This entry was posted in Sharepoint 2010 Server Object Model. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s