3

我正在使用 LINQ 过滤从 Sharepoint WSS3 的listService.GetListItems()方法返回的 XmlNode。

这是它返回的 XML:http: //pastebin.com/mqHcserY

我观察到最后一行与其他行不同,它不包含以下属性。

ows_ContentType
ows_LinkFilenameNoMenu
ows_LinkFilename
ows_BaseName 
ows__EditMenuTableStart

因此,考虑到这一点,我使用 LINQ 过滤结果:

XmlNode items = listService.GetListItems(listName, string.Empty, query, viewFields, string.Empty, queryOptions, g.ToString());

// Namespace for z: prefix
XNamespace xns = "#RowsetSchema";

XElement root;
using (XmlReader xr = new XmlNodeReader(items)) { root = XElement.Load(xr); }

// This query returns XElements that are Folder types
IEnumerable<XElement> result = from child in root.Descendants(xns + "row")
                               where child.Attribute("ows_ContentType").Value != null && child.Attribute("ows_ContentType").Value == "Folder"
                               select child;

foreach (XElement xml in result)
{
    //Exception when attempts to loop final XElement
}

但是,当我遍历结果时,我得到一个NullReferenceException. 在 Foreach 循环中,它会愉快地遍历每个对象,直到到达最后一个对象,然后它会抛出异常。

最后一个对象与其他行不同(我通过消除过程知道这一点,我看到每隔一行都循环过去)并且应该从我的结果中过滤掉,因为它没有“ows_ContentType”属性。

我将 LINQ 更改为where child.Attribute("ows_ContentType").Value != null && child.Attribute("ows_ContentType").Value == "Folder"尝试过滤任何包含空值的内容,但结果相同。我查看了一些示例,并且似乎具有正确的语法。

有人可以解释是什么导致最后一个 XElement 返回 null 吗?我真的不明白为什么它会向<IEnumerable<XElement> result集合中添加一个空实例。

4

4 回答 4

3

调用不存在的属性的值将导致空引用,因为节点根本不存在。

child.Attribute("ows_ContentType").Value

通过调用缺失元素的值引发异常。

改用这个:

child.Attribute("ows_ContentType") != null

实施的:

IEnumerable<XElement> result = from child in root.Descendants(xns + "row")
                           where child.Attribute("ows_ContentType") != null && child.Attribute("ows_ContentType").Value == "Folder"
                           select child;
于 2012-10-25T12:34:38.677 回答
2

您需要检查元素是否为 null 而不是元素的值。

child.Attribute("ows_ContentType") != null && child.Attribute("ows_ContentType").Value == "Folder"
于 2012-10-25T12:33:28.323 回答
1

请注意,LINQ2XML 只允许您使用(string)someXElement(string)someXAttribute如果 XElement 或 XAttribute 为 null,或者 XElement 或 XAttribute 的值(如果存在),则它会给出 null。这意味着您的代码可以缩短使用

IEnumerable<XElement> result = from child in root.Descendants(xns + "row")
                               where (string)child.Attribute("ows_ContentType") == "Folder"
                               select child;
于 2012-10-25T13:39:02.913 回答
0

最后一个节点不包含“ows_ContentType”属性,但您的 where 子句正在查找该缺失属性的值。

可能你需要

where child.Attribute("ows_ContentType") != null 
&& child.Attribute("ows_ContentType").Value == "Folder"
于 2012-10-25T12:34:14.737 回答