Programmatically create SharePoint 2010 content type using XML definition file
-
07-04-2021 - |
Question
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?
Solution
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.
OTHER TIPS
The most common way is to use a feature definition and then activate the feature for your site collection. The xml for the feature will look something like this:
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<!-- Parent ContentType: Document (0x0101) -->
<ContentType ID="0x0101000728167cd9c94899925ba69c4af6743e"
Name="Financial Document"
Group="Financial Content Types"
Description="Base financial content type"
Version="0">
<FieldRefs>
<FieldRef ID="{1511BF28-A787-4061-B2E1-71F64CC93FD5}" Name="OrderDate" DisplayName="Date" Required="FALSE"/>
<FieldRef ID="{060E50AC-E9C1-4D3C-B1F9-DE0BCAC300F6}" Name="Amount" DisplayName="Amount" Required="FALSE"/>
</FieldRefs>
</ContentType>
</Elements>
See the full sample at http://msdn.microsoft.com/en-us/library/ms463449.aspx.
Was there a specific reason you were trying to use the object model instead?