Reputation: 193282
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();
}
}
}
I figured out if I change XDocument to XElement, then it works. Could anyone explain why?
Upvotes: 2
Views: 238
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