title: Turning XDocument/Elements into a C# Class Object
body: <p>I am having a problem trying to read a XML from XDocument, converting the Elements into an actual Class Object. Reason why im not using XmlSerialization is because i need to use PropertyGrid.</p>
  
  <p>Cant get it to create the children with inside a class it self.</p>
  
  <p><strong>Error Given</strong></p>
  
  <pre><code>  System.NullReferenceException occurred
    HResult=0x80004003
    Message=Object reference not set to an instance of an object.
    Source=XmlTest2
    StackTrace:
     at XmlTest2.Program.Main(String[] args) in Program.cs:line 22
  
  var list = q.GetElementsByClass&lt;Targets&gt;();
  foreach (var p in list)
  {
      Console.WriteLine(p.grouping.name);
  }
  </code></pre>
  
  <p><strong>This will work</strong></p>
  
  <pre><code>var list = q.GetElementsByClass&lt;Grouping&gt;();
  foreach (var p in list)
  {
      Console.WriteLine(p.name);
  }
  </code></pre>
  
  <p>Full code and XML located here
  <a href="https://pastebin.com/0TjKsAKH" rel="nofollow noreferrer">XMLFile1.xml</a>
  <a href="https://pastebin.com/UnktaCC9" rel="nofollow noreferrer">Program.cs</a></p>
  
  <pre><code>public T[] GetElementsByClass&lt;T&gt;() where T : class, new()
  {
      Assembly asm = Assembly.GetExecutingAssembly();
      var typeName = typeof(T).Name;
      var type = asm.GetTypes().First(t =&gt; t.Name == typeName);
      if (type == null) throw new ArgumentNullException(nameof(type));
  
      return _doc.Descendants(_parent)
          .Select(item =&gt;
          {
              var p = Activator.CreateInstance(type) as T;
              foreach (var prop in item.Descendants())
              {
                  var pi = p.GetType().GetProperty(prop.Name.LocalName);
                  if (pi == null) continue;
  
                  object newVal = Convert.ChangeType(prop.Value, pi.PropertyType);
                  pi.SetValue(p, newVal, null);
              }
  
              return p;
          }).ToArray();
  }
  </code></pre>