Monday, December 15, 2008

Iterate SharePoint list items using SharePoint web service

Hi all,
here is some chunks of that will help you out to iterate list item in SharePoint list using SharePoint web service. to parse all list items you should know XmlNameSpace from result xml schema,but here in this case I have remove that XmlNameSpace using Regx.so it is easy to iterate result xml schema.

Following example will fetch all list items from SharePoint list and show all title to console.

for better result copy the code and paste it in your console application add necessary assemblies,
include SharePoint list.asmx webrefrence name this reference as "ListService".


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
//List service proxy
using SharePointKingsDemo.ListService;
using System.Net;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;

namespace SharePointKingsDemo
{
///


/// Created By:Jayesh Prajapati.
/// Purpose:how to use SharePoint web service.,how to iterate each row in SharePoint list.
/// iterate each SharePoint list item without xmlname space.
/// This demo will work on .NET framework 3.5
///

class Program
{
//find replace xmlnamespace..
private static readonly Regex StripXmlnsRegex =
new Regex(@"(xmlns:?[^=]*=[""][^""]*[""])",
RegexOptions.IgnoreCase RegexOptions.Multiline RegexOptions.Compiled RegexOptions.CultureInvariant);

//to find and replace short XmlNameSpace like z:,rs: from xmlresponse by GetListItems method
private static readonly Regex removeShortNameSpace = new Regex
(@"(?<lessthan><)(?<closetag>[/])?(?<shortname>\w+:)\s*", RegexOptions.IgnoreCase RegexOptions.Multiline RegexOptions.Compiled RegexOptions.CultureInvariant);


static void Main(string[] args)
{
//list webservice proxy instance..
ListService.Lists listService = new Lists();
CredentialCache credential = new CredentialCache();
//credentials username,password,domain..
NetworkCredential networkCredential = new NetworkCredential("username", "password","domain");
credential.Add(new Uri("http://localhost"),"NTLM",networkCredential);
listService.Credentials = credential;
listService.Url = "http://localhost/_vti_bin/lists.asmx";

//xmldocument to create necessary nodes for getalllistitems method..
XmlDocument xdoc =new XmlDocument();
XmlNode queryNode =xdoc.CreateNode(XmlNodeType.Element,"Query","");

//get all list items whose id is greater than zero i.e all list item..
string strQuery = @"<Where><Gt><FieldRef Name='ID'/><Value Type='Counter'>0</Value></Gt></Where>";
queryNode.InnerXml=strQuery;
XmlNode viewNode = xdoc.CreateNode(XmlNodeType.Element,"ViewFields","");
string strViewFields = "<FieldRef Name=\"ID\" /><FieldRef Name=\"Title\" />";
viewNode.InnerXml=strViewFields;
XmlNode nodeQueryOption = xdoc.CreateNode(XmlNodeType.Element,"QueryOptions","");
nodeQueryOption.InnerXml="<IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns><DateInUtc>TRUE</DateInUtc>";
string rowlimit = "100";
string webid = "";

//get items from test sharepoint list..
XmlNode result = listService.GetListItems("test","", queryNode, viewNode, rowlimit, nodeQueryOption, webid);

//remove namespace xmlnls from result xml..
string xmlResponse = StripXmlnsRegex.Replace(result.InnerXml, "");

//find and replace short XmlNameSpace like z:,rs: from responce with space..
xmlResponse = removeShortNameSpace.Replace(xmlResponse, delegate(Match m)
{
Group closetag = m.Groups["closetag"];
if (closetag.Length !=0)
{
return "</";
}
else
{
return "<";
}

});

//load xml from removed XmlNameSpace and short name of XmlNameSpace..
XDocument xmlDoc = new XDocument();
xmlDoc = XDocument.Parse(xmlResponse);

//iterate each row in sharepoint list.
//in result xml each row is in element "row"
var Items = from item in xmlDoc.XPathSelectElements("//row")
select new
{
//get Title Field of SharePoint list...
Title = Convert.ToString(item.Attribute("ows_Title").Value)
};
//display each item in title field in console..
Array.ForEach(Items.ToArray(), item => Console.WriteLine(item.Title));
Console.ReadLine();


}
}
}

give your comments on this post, for alternate approch to parse web service response using xpath see following article..

http://www.sharepointkings.com/2008/11/how-to-iterate-sharepoint-list-fields.html


2 comments:

Anonymous said...

I like this way of doing it but was unable to convert one little section of this to vb.net

xmlResponse = removeShortNameSpace.Replace(xmlResponse, delegate(Match m)




If you could help me convert that to vb.net that would be great. I am not sure how to to delegate functions. Thanks. Brad.

Jayesh Prajapati said...

Hi brad,
well i am not good at vb.net.
but you can use some online conversion tool and try out it may work for you..

http://joeon.net/post/Tool-to-convert-your-C-to-VB-and-your-VB-to-C.aspx
http://www.developerfusion.com/tools/convert/csharp-to-vb/

-cheers




Share your SharePoint Experiences with us...
As good as the SharePointKings is, we want to make it even better. One of our most valuable sources of input for our Blog Posts comes from ever enthusiastic Visitors/Readers. We welcome every Visitor/Reader to contribute their experiences with SharePoint. It may be in the form of a code stub, snippet, any tips and trick or any crazy thing you have tried with SharePoint.
Send your Articles to sharepointkings@gmail.com with your Profile Summary. We will Post them. The idea is to act as a bridge between you Readers!!!

If anyone would like to have their advertisement posted on this blog, please send us the requirement details to sharepointkings@gmail.com