Bulk Add new items to a SharePoint List using ProcessBatchData

private readonly string BatchXMLBanner =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><ows:Batch OnError=\"Continue\">{0}</ows:Batch>";

private readonly string BatchXMLMethod =
"<Method ID=\"{0}\"><SetList>{1}</SetList><SetVar Name=\"ID\">New</SetVar><SetVar Name=\"Cmd\">Save</SetVar>{2}</Method>";
 
private readonly string BatchXMLSetVar =
"<SetVar Name=\"urn:schemas-microsoft-com:office:office#{0}\">{1}</SetVar>";

Batch = buildBatch(dataTable, TargetList.ID);
BatchReturn = oWeb.ProcessBatchData(Batch);

private string buildBatch(DataTable dataTable, Guid guid)
{
    StringBuilder XMLSetVarLines = new StringBuilder();
    StringBuilder XMLSetMethods = new StringBuilder();

    int methodID = 0;

    foreach(DataRow row in dataTable.Rows)
    {
        foreach(DataColumn column in dataTable.Columns)
        {
            var fieldname = column.ColumnName;
            var fieldvalue = row[fieldname].ToString().Replace("&", "&amp");
            XMLSetVarLines.Append(String.Format(BatchXMLSetVar, fieldname, fieldvalue));
        }

        XMLSetMethods.Append(String.Format(BatchXMLMethod, methodID, guid, XMLSetVarLines));

        methodID++;

        XMLSetVarLines.Length = 0;
    }
    return (String.Format(BatchXMLBanner, XMLSetMethods));
}

2 Comments


  1. pungi
    Dec 30, 2011

    I don’t get this…MS provides a ProcessBatchData() and to use it you need to build this XML crap? Come-on, show a little creativeness!


  2. aaron
    Jan 08, 2012

    Not sure if your comment is directed at me or Microsoft but yes you do need to build the XML to use it (also shown at http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.processbatchdata.aspx).

    Whilst it may not be the most intuitive process its purpose is to allow the creation of the XML from various sources / streams and bulk process the tasks versus a foreach X in XXX Item.Add.

    The performance difference is significant, and can be further used to you advantage to bulk delete items – for instance you can use ProcessBatchData to delete a million items in a fraction of the time it would take by any of the other object model methods.

Leave a Reply