Edward Tanguay
Edward Tanguay

Reputation: 193282

Why does trying to access an attribute in LINQ-to-XML give me an error?

According to my LINQ book, this slightly altered example should work.

Why does it tell me "Object reference not set to an instance of an object"?

using System;
using System.Xml.Linq;

namespace TestNoAttribute
{
    class Program
    {
        static void Main(string[] args)
        {

            XDocument xdoc = new XDocument(
                new XElement("employee",
                    new XAttribute("id", "23"),
                    new XElement("firstName", new XAttribute("display", "true"), "Jim"),
                    new XElement("lastName", new XAttribute("display", "false"), "Smith")));

            XElement element = xdoc.Element("firstName");
            XAttribute attribute = element.Attribute("display"); //error

            Console.WriteLine(xdoc);

            Console.ReadLine();

        }
    }
}

Partial Answer:

I figured out if I change XDocument to XElement, then it works. Could anyone explain why?

Upvotes: 2

Views: 238

Answers (2)

bruno conde
bruno conde

Reputation: 48265

You are accessing a child element of xdoc that doesn't exist. Try one level down:

XElement element = xdoc.Element("employee").Element("firstName");

or

XElement element = xdoc.Descendants("firstName").FirstOrDefault();

Upvotes: 4

Marc
Marc

Reputation: 9344

See this on MSDN as to why. It explicitly explains their 'idiom' on why they felt returning a null element when the name is not found was beneficial.

Upvotes: 2

Related Questions