Question

I have a list with 2 text fields, and a choice field. How do I use the Lists.asmx web service to insert a new item? I can make a web reference to the lists.asmx service, so you can assume that this is known.

I would like a complete example including code and the XML for the CAML query. Ideally the sample would use C#.

Was it helpful?

Solution

Using the Lists web service to insert item into a SharePoint list can indeed be tricky. Since this method is of the form: XML in, XML out, it can be hard to get the parameters right.

First you should take a look at the list definition. It can be retrieved with the method GetList(), as shown below:

XmlNode listXml = sharePointLists.GetList(listName);
File.WriteAllText("listdefinition.xml", listXml.OuterXml);

Important here are the names of the fields and their data types. Field names will never be the same as the ones you see in the SharePoint GUI. A good example is the Title field which is used for the first field of the list.

Now that you know that, you can create the query to go to SharePoint. An example:

<Batch OnError="Continue">
    <Method ID="1" Cmd="New">
        <Field Name="Title">Abcdef</Field>
        <Field Name="Project_x0020_code">999050</Field>
        <Field Name="Status">Open</Field>    
    </Method>
</Batch>

The Batch element is the root element of the XML. Inside you can put different Methods. These should get a unique ID (which is used to report errors back to you) and a command, which can for instance be "New" or "Update". Inside the Method, you put Field elements that specify the value for each field. For instance, the Title field gets the value "Abcdef". Be careful to use the exact name as it is returned by GetList().

To execute the query on SharePoint, use the UpdateListItems() method:

XmlNode result = sharePointLists.UpdateListItems(listDefinition.Name, updates);

The return value is an XML fragment containing the status of each update. For instance:

<Results xmlns="http://schemas.microsoft.com/sharepoint/soap/">
    <Result ID="1,New">
    <ErrorCode>0x00000000</ErrorCode>
    <z:row ows_ContentTypeId="0x010036F3F587127F1A44B8BA3FEFED4733C6" 
         ows_Title="Abcdef" 
         ows_Project_x0020_code="999050" 
         ows_Status="Open" 
         ows_LinkTitleNoMenu="Abcdef" 
         ows_LinkTitle="Abcdef" 
         ows_ID="1005"            
         ... 
         xmlns:z="#RowsetSchema" />
    </Result>
</Results>

You can parse this and look at the ErrorCode to see which methods failed.

In practice I have created a wrapper class that takes care of all the dirty details for me. Unfortunately this is owned by my employer so I cannot share it with you.

This wrapper class is part of an internal utility that is used to retrieve information from our project database and post it to SharePoint. Since it was developed during company time, I'm not allowed to post it here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top