Ads

Wednesday, 15 May 2013

Use SharePoint List Web Service to get list items by using GetListItems method

Lets 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.

No comments:

Post a Comment

Ads