简体   繁体   中英

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. When I use the Where() method, I manage to find the one item successfully. Using First() returns that item successfully, and if I use Any() it returns true. However if I use Count() or ToList() it returns 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". All your LINQ queries ("where" in this case) will be only executed if you actually use the result.

There exists an item in your list which has an attribute which returns 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.

ToList() will loop over all elements --> one Attribute returns null and the call of the .ToLower instance method will result in a NullReferenceException

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM