我正在使用C#来调用Sharepoint Web服务。我想获得一个Sharepoint列表,然后对列表中的每个项目,将其属性写入控制台。当我使用foreach
遍历属性时,我不断得到“对象引用未设置为对象的实例”。代码如下:
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();
}
}
}
我认为它抛出了异常,因为某些列表项的某些属性为Null
。但我无法弄清楚如何在foreach
迭代中检查属性是否为空。
答案 0 :(得分:5)
看一下这个例子和article。
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);
}
}