我在尝试从XDocument读取XML时遇到问题,将Elements转换为实际的Class对象。我不使用XmlSerialization的原因是因为我需要使用PropertyGrid。
不能让它自己在课堂上创造孩子。
错误
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);
}
这将有效
var list = q.GetElementsByClass<Grouping>();
foreach (var p in list)
{
Console.WriteLine(p.name);
}
完整的代码和XML位于此处 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();
}