今天有个网友问如何历遍对象的所有公共属性,并且生成XML。采用序列化方式的话比较简单,我写个手工解析的例子,这样能让初学者更加理解也比较灵活,记录一下吧或许会有人用到。
对象模型:
public class Master { public string Description { get; set; } public List<Slave> Slaves { get; set; } } public class Slave { public int ID { get; set; } public string Name { get; set; } }
解析代码:
//生成数据 Master master = new Master(); master.Description = "ABCD"; master.Slaves = new List<Slave>(); master.Slaves.Add(new Slave { Name = "aaa", ID = 1 }); master.Slaves.Add(new Slave { Name = "bbb", ID = 2 }); master.Slaves.Add(new Slave { Name = "ccc", ID = 3 }); StringBuilder sb = new StringBuilder("<Root> ");
//生成XML foreach (PropertyInfo pi in master.GetType().GetProperties()) { if (pi.PropertyType.IsGenericType) { sb.AppendLine($"<{pi.Name}>"); foreach (object items in (pi.GetValue(master, null) as IEnumerable<object>)) { sb.AppendLine($"<{items.GetType().Name}>"); foreach (PropertyInfo item in items.GetType().GetProperties()) { sb.AppendLine($"<{item.Name}>{item.GetValue(items, null)}</{item.Name}>"); } sb.AppendLine($"</{items.GetType().Name}>"); } sb.AppendLine("</{pi.Name}>"); } else { sb.AppendLine($"<{pi.Name}>{pi.GetValue(master, null)}</{pi.Name}>"); } } sb.AppendLine("</Root>"); MessageBox.Show(sb.ToString());
生成的XML结构:
<Root> <Description>ABCD</Description> <Slaves> <Slave> <ID>1</ID> <Name>aaa</Name> </Slave> <Slave> <ID>2</ID> <Name>bbb</Name> </Slave> <Slave> <ID>3</ID> <Name>ccc</Name> </Slave> </Slaves> </Root>