多層實體轉xml,泛型轉xml都可用,完善中.... ...
public static XElement ToXElement<T>(T entity, XElement element = null, XElement parent = null, XElement children = null) where T : new() { if (element == null) element = new XElement(entity.GetType().Name); PropertyInfo[] properties = entity.GetType().GetProperties(); XElement innerElement = null; object propertyValue = null; foreach (PropertyInfo property in properties) { if (property.GetValue(entity) == null) continue; //當屬性為字元串時 if (property.PropertyType == typeof(string) || property.GetValue(entity).GetType() == typeof(string)) { propertyValue = property.GetValue(entity); innerElement = new XElement(property.Name, propertyValue); if (children != null) children.Add(innerElement); else element.Add(innerElement); }//當該屬性為List泛型時,或者為引用類型。 else if (property.PropertyType.IsGenericType || property.PropertyType.IsClass) { if (property.PropertyType.IsClass) { if (children != null) parent = children; children = new XElement(property.Name); } else children = new XElement(property.GetValue(entity).GetType().Name); if (property.GetValue(entity).GetType().IsGenericType) { foreach (object o in (property.GetValue(entity) as IEnumerable)) { ToXElement(o, element, parent, children); } } else { return ToXElement(property.GetValue(entity), element, parent, children); } } else { propertyValue = property.GetValue(entity); innerElement = new XElement(property.Name, propertyValue); if (children != null) children.Add(innerElement); else element.Add(innerElement); } } if (children != null) { if (parent != null) parent.Add(children); else parent = children; element.Add(parent); } return element; }