Programmatically create SharePoint 2010 content type using XML definition file

Marcus Blomberg picture Marcus Blomberg · Dec 28, 2011 · Viewed 12.3k times · Source

Is there any way to programmatically create a SharePoint 2010 content type using an XML definition file? SPFields can be added in the following way:

SPContext.Current.Web.Fields.AddFieldAsXml("<xml />");

Is there any similar way to programmatically add content types to a site collection/site?

Answer

Nigel Whatling picture Nigel Whatling · Dec 29, 2011

You can programmatically create/add content types, but not using XML definition (as far as I'm aware). You have to construct it, add it to a content type collection, and manually add your field references to the field links collection.

A rough example would be:

using (SPSite site = new SPSite("http://localhost"))
{
    using (SPWeb web = site.OpenWeb())
    {
        SPContentType contentType = new SPContentType(web.ContentTypes["Document"], web.ContentTypes, "Financial Document");
        web.ContentTypes.Add(contentType);
        contentType.Group = "Financial Content Types";
        contentType.Description = "Base financial content type";
        contentType.FieldLinks.Add(new SPFieldLink(web.Fields.GetField("OrderDate")));
        contentType.FieldLinks.Add(new SPFieldLink(web.Fields.GetField("Amount")));
        contentType.Update();
    }
}

You don't get to control the content type IDs this way though. I prefer using features as per Greg Enslow's response.