Sunday, April 26, 2009

How to query SharePoint list data using web service

There are scenarios where we need to extract or query data of SharePoint using some custom code - say in console or winform application.

Here is the sample code and procedure

Add the web reference for the web service in your .net project http:///_vti_bin/Lists.asmx with alias as MyLists

Now use the below code

MyLists.Lists listService = new MyLists.Lists();
listService.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
//
listService.Url = "http:///_vti_bin/Lists.asmx";
// Instantiate an XmlDocument object
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
//
string listName = "Purchase Orders";
string viewName = "";//blank for default
//
/*Use the CreateElement method of the document object to create elements for the parameters that use XML.*/
XmlElement query = xmlDoc.CreateElement("Query");
XmlElement viewFields = xmlDoc.CreateElement("ViewFields");
XmlElement queryOptions = xmlDoc.CreateElement("QueryOptions");
//
//The below query applies filter "where Field1 = 1"
query.InnerXml = "" +
"1
";
//The below string specified which are the fields to be returned in the result
//apart from the default fields
viewFields.InnerXml = "";
queryOptions.InnerXml = "FALSETRUE";
//
/* Declare an XmlNode object and initialize it with the XML response from the GetListItems method.
* The last parameter specifies the GUID of the Web site containing the list.
* Setting it to null causes the Web site specified by the Url property to be used.*/
System.Xml.XmlNode nodeListItems = listService.GetListItems(listName, viewName, query, viewFields, rowLimit, queryOptions);
//
DataSet ds = new DataSet();
XmlTextReader myReader = new XmlTextReader(new MemoryStream(ASCIIEncoding.Default.GetBytes(nodeListItems.OuterXml)));
ds.ReadXml(myReader);

No comments: