Tuesday, April 29, 2014

Adding, updating and deleting SPListItems using the SharePoint list webservice in combination with XDocument

Quick code snippet which does the following:

- generates a Batch element of type XDocument (i choose for XDocument rather than XmlDocument because it makes it so much simpler to build up the document
- converts the XDocument object to an XmlDocument using an XmlReader



XmlDocument doc;

XDocument xDoc = new XDocument(
    new XElement("Batch", new XAttribute("OnError", "Continue"),

        // Add new item
        new XElement("Method", new XAttribute("ID", "1"), new XAttribute("Cmd", "New"),
            new XElement("Field", "test0", new XAttribute("Name", "Title")),
            new XElement("Field", "Update", new XAttribute("Name", "UserAction")),
            new XElement("Field", "(GAR-2313)", new XAttribute("Name", "OldValue")),
            new XElement("Field", "(SWX-9582)", new XAttribute("Name", "NewValue"))
        ),

        // Updates item: set column 'ProjectStatus' with value 'CLOSED' for item with ID 4
        new XElement("Method", new XAttribute("ID", "2"), new XAttribute("Cmd", "Update"),
            new XElement("Field", "4", new XAttribute("Name", "ID")),
            new XElement("Field", "CLOSED", new XAttribute("Name", "ProjectStatus"))
        ),

        // Delete items with ID 11 and 17 
        new XElement("Method", new XAttribute("ID", "3"), new XAttribute("Cmd", "Delete"),
            new XElement("Field", "11", new XAttribute("Name", "ID"))),
        new XElement("Method", new XAttribute("ID", "4"), new XAttribute("Cmd", "Delete"),
            new XElement("Field", "11", new XAttribute("Name", "ID")
            )
        )
    )
);

using (XmlReader xmlReader = xDoc.CreateReader())
{
    doc = new XmlDocument();
    doc.Load(xmlReader);
}

// assuming a web reference called 'ListWebService' is present..
using (ListWebService.Lists listsWebSvc = new ListWebService.Lists())
{
    //This passes the default user credentials of the user to the web service system
    listsWebSvc.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

    // replace '_listWebSvcUrl' with the url of your list
    listsWebSvc.Url = _listWebSvcUrl;

    // replace '_listName' with the name of your list
    listsWebSvc.UpdateListItems(_listName, doc); 
}