今天有个网友问如何历遍对象的所有公共属性,并且生成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 = "cccc", ID = 3 }); StringBuilder sb = new StringBuilder("<Root>\r\n"); //获取对象所有公共属性 foreach (PropertyInfo pi in master.GetType().GetProperties()) { //判断属性是否为集合类型 if (pi.PropertyType.IsGenericType) { sb.AppendLine($"<Items name=\"{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("</Items>"); } else { sb.AppendLine($"<{pi.Name}>{pi.GetValue(master, null)}</{pi.Name}>"); } } sb.AppendLine("</Root>"); MessageBox.Show(sb.ToString());
生成的XML结构:
<Root> <Description>ABCD</Description> <Items name="Slaves"> <Slave> <ID>1</ID> <Name>aaa</Name> </Slave> <Slave> <ID>2</ID> <Name>bbb</Name> </Slave> <Slave> <ID>3</ID> <Name>cccc</Name> </Slave> </Items> </Root>
原文地址:https://www.cnblogs.com/MuNet/p/11479895.html
时间: 2024-11-09 06:09:43