Programmatically create SharePoint 2010 content type using XML definition file

12,285

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.

Share:
12,285
Marcus Blomberg
Author by

Marcus Blomberg

Updated on June 14, 2022

Comments

  • Marcus Blomberg
    Marcus Blomberg about 2 years

    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?