Pages

Friday, October 15, 2010

SharePoint - AddingFieldAsXML

Hi,

I was basically trying to hook up a SharePoint Field to the one of document library of my site , I know there are different approaches like using UI, writing code.. that one can follow to add desired field directly
but here is something new I came across , Adding Field as XML..:)
what this approach is all about? this is like a creating a Site Column (Field Element) by using feature (I hope I am right)
we can  create a field on the fly and provide some attributes like ID, Type, DisplayName, Name, Required….
this is what I did for attaching a Note Type Field to one of doc Lib

using (SPSite site = new SPSite(http://YourSite))
{
   using (SPWeb web = site.RootWeb)
   {
      SPList docList = web.Lists["Documents"];
      if (docList != null)
      {
         XmlDocument doc = new XmlDocument();
         XmlElement xmlElement = doc.CreateElement("Field");
         xmlElement.SetAttribute("ID", "0F7A6C90-8715-4aa7-90FE-3491DC8953C7");   //ID can be any GUID        
         xmlElement.SetAttribute("Type", "Note");
         xmlElement.SetAttribute("Name", "UserNote");
         xmlElement.SetAttribute("DisplayName", "UserNote");
         xmlElement.SetAttribute("Required", "FALSE");

         docList.Fields.AddFieldAsXml(xmlElement.OuterXml);
         docList.Update();
                           
         Console.WriteLine("Added Field As XML");
      }
   }
}

No comments:

Post a Comment