[英]C# Xml.Linq collection with one item returns “Object reference not set to an instance of an object” using .ToList()
我有一個帶有許多XML元素的List<XElement>
。 當我使用Where()
方法時,我設法成功找到了一項。 使用First()
成功返回該項目,如果我使用Any()
則返回true。 但是,如果我使用Count()
或ToList()
它將返回Object reference not set to an instance of an object.
提前謝謝了。
//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");
}
這應該工作:
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");
我認為您的一個或多個XElement對象沒有名為“ name”的屬性。 僅當您實際使用結果時,才會執行所有LINQ查詢(在這種情況下為“ where”)。
您的列表中存在一個項目,該項目的屬性返回null
。 這不是第一個。 .Any()
和First()
都將在Enumerable上循環,直到找到第一個滿足條件的元素為止。
ToList()
將遍歷所有元素->一個Attribute返回null
並且.ToLower
實例方法的調用將導致NullReferenceException
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.