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?