Thursday, December 17, 2009

SharePoint List Web Service GetListItems



In this post, I’ going to discuss how we can retrieve data from a SharePoint List using its Web Services. First to know about SharePoint Web Services please refer this. We can user List Web Service which provides methods for working with SharePoint Lists, Content Types, List Items, and Files to read a List. Here we are going to use GetListItems method.

To use the above method we should know the GUIDs of the target list and view. Please follow my article on SharePoint List GUIDs to see how we can get them.

This is how you can Add Web Reference; I’ll get created Web Site Project in Visual studio to illustrate. Actually it is simple, first click on Add Web Reference and give the URL to the Web Service.





This is a sample code to read SharePoint list,
    public void getListData()
    {
        WS_Lists.Lists myservice = new WS_Lists.Lists();
        myservice.Credentials = System.Net.CredentialCache.DefaultCredentials;
        myservice.Url = "http://merdev-moss:5050/testsara/_vti_bin/Lists.asmx";
        try
        {
            /* Assign values to pass the GetListItems method*/
            string listName = "{5C65CB1A-2E1B-488A-AC07-B115CD0FC647}";
            string viewName = "{75E689B4-5773-43CB-8324-58E42E1EB885}";
            string rowLimit = "100";

            // Instantiate an XmlDocument object
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            System.Xml.XmlElement query = xmlDoc.CreateElement("Query");
            System.Xml.XmlElement viewFields = xmlDoc.CreateElement("ViewFields");
            System.Xml.XmlElement queryOptions = xmlDoc.CreateElement("QueryOptions");

            /*Use CAML query*/
            query.InnerXml = "<Where><Gt><FieldRef Name=\"ID\" />" +
            "<Value Type=\"Counter\">0</Value></Gt></Where>";
            viewFields.InnerXml = "<FieldRef Name=\"Title\" />";
            queryOptions.InnerXml = "";

            System.Xml.XmlNode nodes = myservice.GetListItems(listName, viewName, query, viewFields, rowLimit, null, null);

            foreach (System.Xml.XmlNode node in nodes)
            {
                if (node.Name == "rs:data")
                {
                    for (int i = 0; i < node.ChildNodes.Count; i++)
                    {
                        if (node.ChildNodes[i].Name == "z:row")
                        {
                            Response.Write(node.ChildNodes[i].Attributes["ows_Title"].Value + "</br>");
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }
In the above code I have use CAML queries to get the result. It will return all the result because I’m searching for Items which has ID greater than 0. It is always true. If you want to know how to write CAML quires easily please refer my article on CAML & SPQuery in SharePoint.

31 comments:

  1. Hi Saranga,

    I have added a link to this post in the SharePoint Resources section of Web-Resource.org on the following page:

    SharePoint Resources

    Thanks

    ReplyDelete
  2. how add alert to list element, but using webservice ? Some help please :)

    ReplyDelete
  3. Thanks Saranga! :) This helped me out on a project I was working on :)

    ReplyDelete
  4. Thanks for your post Saranga .. the more good examples the better!

    I’m currently getting the list of user defined columns for a Document Library by calling SelectNodes on the XML returned from GetList on the site where the SourceID is used in the XPath expression to find the user defined columns:

    XmlNode objFieldCollection = m_FieldList.GetList( strCurrentDocLib );
    XmlDocument objXdocument = new XmlDocument();
    m_objXmlNamespaceManager = new XmlNamespaceManager( objXdocument.NameTable );
    m_objXmlNamespaceManager.AddNamespace( "sp", "http://schemas.microsoft.com/sharepoint/soap/" );
    objXdocument.LoadXml( objFieldCollection.OuterXml );

    XmlNode objIdNode = objXdocument.SelectSingleNode( "//sp:List", m_objXmlNamespaceManager );\
    string strListID = objIdNode.Attributes[ "ID" ].InnerText;
    string xPath = String.Format( "//sp:Field[@SourceID='{0}' or @SourceID='{1}']",
    strListID.ToLower(), strListID.ToUpper() );

    XmlNodeList objFieldCollectionList = objXdocument.SelectNodes( xPath, m_objXmlNamespaceManager );

    foreach (XmlNode node in objFieldCollectionList)
    ParseFieldData( node.OuterXml );

    The problem is when a user adds a column from the Site Column Gallery the SourceID is different for those columns so this doesn’t work anymore. I was able to get it working by creating a more complex XPath but I’m not confident this whole approach is correct.

    Is this the right / best way to get the list of user defined columns for a Document Library?

    Should I use GetListItems instead? If so, can you provide a code snippet to that effect?

    Thanks in advance for any feedback!
    Karl

    ReplyDelete
  5. Hi Saranga,

    I tried testing your solution and it it worked like a charm. I have a scenario in which I have to provide my SP list information to teams working on Java. I was thinking of exposing the _vti_bin/lists.asmx to them so they dont bug me each time they need something. The way I was thinking it would actually work would be:
    http://servername/_vti_bin/lists.asmx and provide listName as a query string and boom. It hasnt turned out to be that way, I am sure there has to be a way to provide all the information the way I am thinking. Is there anything you may think on top of your head.

    Thanks.

    ReplyDelete
  6. Thanks, Worked perfectly,
    keep the good work posted..

    ReplyDelete
  7. @ Akshaya Mashankar,
    Thank you for you comment.

    ReplyDelete
  8. Hi Saranga,

    I would like ask, is there anyway for me to extract out lists item from past instances? (Assuming each instance = 1 date)

    I would like to extract all the list items from all the past dates (all the past instances).

    is it possible?

    Thank you very much,

    Warmest Regards,
    Michael Lim

    ReplyDelete
  9. Where / How do I define WS_Lists

    ReplyDelete
  10. @ Anonymous,
    WS_Lists is the Web Reference, please check the screen-shots.

    ReplyDelete
    Replies
    1. I get the referenece to WS_Lists, but now it is unable to find Lists reference? What am I missting?

      Delete
  11. Hi
    I am working on an infopath form which has a save button.
    On click of save, I update certain set of list columns using "updatelistitems"
    method of lists.asmx. It works fine,when a new form is being created. But, it doesn't work, when the same form is being updated(open the created form,
    change values& save). Any idea, what could be the problem?
    Could you also pls give your mailid,So thr I can send the codewith screen shots of the form.

    ReplyDelete
  12. Hi
    I am not able to see the Column "ID" in my list
    how can enable it please help me in it

    ReplyDelete
  13. Thank you very much...... sir !!!

    ReplyDelete
  14. Hi Saranga,

    Instead of hard coding the ListName (which is List ID value) in your code sample you could probably get the list collection using GetListCollection method of Lists.asmx Web Service http://msdn.microsoft.com/en-us/library/websvclists.lists.getlistcollection.aspx to dynamically get the right List ID for you list name.

    Best wishes,
    Slava

    http://wyldesharepoint.blogspot.com

    ReplyDelete
  15. @ garry,
    You are welcome..!

    @ Slava G,
    Thanks for the information. Yes it is better way to get the GUID. I'll update my post if time permits.

    ReplyDelete
  16. Thanks for the Post..:)
    but I got blocked with "{"Exception of type 'Microsoft.SharePoint.SoapServer.SoapServerException' was thrown." exception message. Any idea to resolve this issue.

    ReplyDelete
  17. This code worked for me for months and months...now all of a sudden, no data is being returned...I checked the list in SPS 2007, the data is there, but this code is not finding anything anymore...I get #whitespace and other stuff...but no data in this code is working?

    ReplyDelete
  18. This code worked for me for months and months...now all of a sudden, no data is being returned...I checked the list in SPS 2007, the data is there, but this code is not finding anything anymore...I get #whitespace and other stuff...but no data in this code is working?

    ReplyDelete
  19. This code worked for me for months...and now no data is returned, as far as I know and pretty sure nothing has changed...but no data is returned...not getting errors, but list still exists in sharepoint 2007, but nothing is being returned...i see references to #whitespace - whats going one?

    ReplyDelete
  20. thanks for the post, code works great ....

    ReplyDelete
  21. thanks for the post .. code works great

    ReplyDelete
  22. For me, the signature for GetListItems method is

    public System.Xml.Linq.XElement GetListItems(string listName, string viewName, System.Xml.Linq.XElement query, System.Xml.Linq.XElement viewFields, string rowLimit, System.Xml.Linq.XElement queryOptions, string webID)

    It use XElement, not XmlElement neither XmlNOde.

    And I get the same error about it.

    ReplyDelete
  23. Please can you share the entire CAML query?

    Online I'm finding code examples, but nowhere showing the complete CAML query.

    Thanks
    -Simon

    ReplyDelete
  24. gets "{"Exception of type 'Microsoft.SharePoint.SoapServer.SoapServerException' was thrown." exception message on retrieving items from a SharePoint 2007calendar with 1000 items... i have indexed the column and the threshold limit has not yet touched.. Kindly provide some input

    ReplyDelete