Turning XDocument/Elements into a C# Class Object

1

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.

Cant get it to create the children with inside a class it self.

Error Given

  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<Targets>();
foreach (var p in list)
{
    Console.WriteLine(p.grouping.name);
}

This will work

var list = q.GetElementsByClass<Grouping>();
foreach (var p in list)
{
    Console.WriteLine(p.name);
}

Full code and XML located here XMLFile1.xml Program.cs

public T[] GetElementsByClass<T>() where T : class, new()
{
    Assembly asm = Assembly.GetExecutingAssembly();
    var typeName = typeof(T).Name;
    var type = asm.GetTypes().First(t => t.Name == typeName);
    if (type == null) throw new ArgumentNullException(nameof(type));

    return _doc.Descendants(_parent)
        .Select(item =>
        {
            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();
}
c#
linq-to-xml
changetype
asked on Stack Overflow Jun 22, 2017 by Proxicide • edited Jun 22, 2017 by Proxicide

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0