Musings by Generator

Development, Life and everything else in S.A.

removing taxonomy values from an SPListItem taxonomy Field.

I was asked to write a pretty simple application that would browse a specific document Library, look for the taxonomy fields that have either “All” or “Not Applicable” for a document and remove the term.

After spending hours browsing the forums for an answer, it came across as a simple solution, and I did find this by trying it as a last resort. This is just the code you will need to actually do the work on the site, you will need to write code to connect and open the web as well which I haven’t included here.

All you need to do is use the TaxonomyField to create a new TaxonomyFieldValue or TaxonomyFieldValueCollection, if you allow multiple values in the field, and use TaxonomyField.SetFieldValue(SPListItem item, TaxonomyFieldValue field) or TaxonomyField.SetFieldValue(SPListItem item, TaxonomyFieldValueCollection collection) .

SPDocumentLibrary library = list as SPDocumentLibrary;

bool changesMade = false;

foreach (SPListItem item in library.Items)
{
    changesMade = false;

    foreach (SPField field in item.Fields)
    {
        if (field is TaxonomyField)
        {
            TaxonomyField taxField = field as TaxonomyField;

            if(item[field.Id] != null)
            {
                if (taxField.AllowMultipleValues)
                {
                    TaxonomyFieldValueCollection currentCollection = item[field.Id] as TaxonomyFieldValueCollection;

                    if (currentCollection.Count(val => val.Label.Equals("All") || val.Label.Equals("Not Applicable")) > 0)
                    {
                        TaxonomyFieldValueCollection taxCollection = new TaxonomyFieldValueCollection(taxField);
                        taxField.SetFieldValue(item, taxCollection);

                        changesMade = true;
                    }
                }
                else
                {
                    TaxonomyFieldValue currentValue = item[field.Id] as TaxonomyFieldValue;

                    if (currentValue.Label.Equals("All") || currentValue.Label.Equals("Not Applicable"))
                    {
                        TaxonomyFieldValue taxValue = new TaxonomyFieldValue(taxField);
                        taxField.SetFieldValue(item, taxValue);

                        changesMade = true;
                    }
                }
            }
        }
    }

    if (changesMade)
        item.Update();
}
« Newer Posts