Add list from Xml node by client object model
Following XElement structure as xList:
<List Title="My Title" Url="mylisturl" Description="Some description" ListTemplateType="104" OnQuickLaunch="TRUE">
<Fields>
<Field DisplayName='Start Date' Name='StartDate' Type='DateTime' Required='TRUE' Format='DateOnly'/>
</Fields>
</List>
public static void AddListFromListElement(string webUrl, XElement xList)
{
//get basic list attributes
string listName = xList.Attribute("Title").Value;
string listUrl = xList.Attribute("Url").Value;
int listTemplateType = Convert.ToInt32(xList.Attribute("ListTemplateType").Value);
bool listQuickLaunch = Convert.ToBoolean(xList.Attribute("OnQuickLaunch").Value);
string listDescription = xList.Attribute("Description").Value;
//get fields
IEnumerable<XElement> xFields = xList.Elements("Fields").Elements("Field");
AddListToWeb(webUrl, listName, listUrl, listTemplateType, listQuickLaunch, listDescription, xFields);
}
public static void AddListToWeb(string webUrl, string listName, string listUrl, int listTemplateType, bool listQuickLaunch, string listDescription, IEnumerable<XElement> xFields)
{
ClientContext context = new ClientContext(webUrl);
Web web = context.Web;
IEnumerable<List> result = context.LoadQuery(web.Lists.Include(myList => myList.Title,
myList => myList.Id,
myList => myList.DefaultDisplayFormUrl
));
context.ExecuteQuery();
//Create list if doesn't exist
List list = result.FirstOrDefault(myList => myList.Title == listName);
if (list == null)
{
ListCreationInformation creationInfo = new ListCreationInformation();
creationInfo.Title = listName;
creationInfo.Url = listUrl;
creationInfo.TemplateType = listTemplateType;
list = web.Lists.Add(creationInfo);
list.Description = listDescription;
list.OnQuickLaunch = listQuickLaunch;
list.Update();
context.ExecuteQuery();
}
//Add fields
if (xFields != null)
{
foreach (XElement xField in xFields)
{
string fldName = xField.Attribute("Name").Value;
string fldDisplayName = xField.Attribute("DisplayName").Value;
IEnumerable<Field> fields = context.LoadQuery(list.Fields.Include(f => f.InternalName));
context.ExecuteQuery();
Field existingField = fields.FirstOrDefault(f => f.InternalName == fldName);
if (existingField == null)
{
string fieldXml = Regex.Replace(xField.ToString(), fldDisplayName, fldName);
//internal name is derived from 'DisplayName' ('InternalName' attribute not working), DisplayName is overriden later as 'Title'
Field fld = list.Fields.AddFieldAsXml(fieldXml, true, AddFieldOptions.DefaultValue);
fld.Title = fldDisplayName;
fld.Update();
context.ExecuteQuery();
}
}
}
}