[英]C# Xml.Linq collection with one item returns “Object reference not set to an instance of an object” using .ToList()
I have a List<XElement>
with a number of XML elements. 我有一个带有许多XML元素的
List<XElement>
。 When I use the Where()
method, I manage to find the one item successfully. 当我使用
Where()
方法时,我设法成功找到了一项。 Using First()
returns that item successfully, and if I use Any()
it returns true. 使用
First()
成功返回该项目,如果我使用Any()
则返回true。 However if I use Count()
or ToList()
it returns Object reference not set to an instance of an object.
但是,如果我使用
Count()
或ToList()
它将返回Object reference not set to an instance of an object.
Many thanks in advance. 提前谢谢了。
//Elements:
<meta name="ncc:sidebars" content="0" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="ncc:setInfo" content="1 of 1" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="ncc:tocItems" content="12" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="ncc:totalTime" content="8:02:54" xmlns="http://www.w3.org/1999/xhtml" />
<!-- another 30 other elements... -->
<meta http-equiv="Content-type" content="text/html; charset=ISO-8859-1" xmlns="http://www.w3.org/1999/xhtml" />
public static List<XElement> GetElements(this List<XElement> els, String nameTag)
{
var elementsFound = els.Where(e => e.Attribute("name").Value.ToLower() == "ncc:totaltime");
if (elementsFound.Any())
return elementsFound.ToList();
else
throw new Exception("Some text");
}
this should work: 这应该工作:
var elementsFound = els.Where(e => e.Attribute("name") != null && e.Attribute("name").Value.ToLower() == nameTag);
if (elementsFound.Any())
return elementsFound.ToList();
else
throw new Exception("Some text");
I think one or more of your XElement objects do not have a attribute named "name". 我认为您的一个或多个XElement对象没有名为“ name”的属性。 All your LINQ queries ("where" in this case) will be only executed if you actually use the result.
仅当您实际使用结果时,才会执行所有LINQ查询(在这种情况下为“ where”)。
There exists an item in your list which has an attribute which returns null
. 您的列表中存在一个项目,该项目的属性返回
null
。 It is not the first one. 这不是第一个。
.Any()
and First()
will both loop just over the Enumerable until the first element is found which fulfills the condition. .Any()
和First()
都将在Enumerable上循环,直到找到第一个满足条件的元素为止。
ToList()
will loop over all elements --> one Attribute returns null
and the call of the .ToLower
instance method will result in a NullReferenceException
ToList()
将遍历所有元素->一个Attribute返回null
并且.ToLower
实例方法的调用将导致NullReferenceException
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.