I’m using C# to call Sharepoint web services. I want to get a Sharepoint list, and then for each item in the list, write its attributes to the console. I keep getting an “Object reference not set to an instance of an object” when I iterate through the attributes with foreach. Code as follows:
class Program
{
static void Main(string[] args)
{
try
{
cSharpTest_service.Lists lists = new cSharpTest_service.Lists();
lists.Url = "http://wsssandbox/sites/cSharp/_vti_bin/lists.asmx";
lists.Credentials = System.Net.CredentialCache.DefaultCredentials;
System.Xml.XmlNode listData = lists.GetListItems("cSharpTestList", "", null, null, "", null, "");
foreach (System.Xml.XmlNode iterateNode in listData)
{
Console.WriteLine("--NODE--");
System.Xml.XmlAttributeCollection attrs = iterateNode.Attributes;
foreach (System.Xml.XmlAttribute attr in attrs)
{
Console.WriteLine("Name:");
Console.WriteLine(attr.Name);
Console.WriteLine("Value:");
Console.WriteLine(attr.Value);
}
}
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadLine();
}
}
}
I think it’s throwing the exception because some of the attributes are Null for some of the list items. But I can’t figure out how to check whether or not the attribute is null as part of the foreach iteration.
Take a look at this example and this article.