public static string GetDifferenceXml(object oldObj, object newObj) { var objectType = newObj.GetType(); using (var stringWriter = new Utf8StringWriter()) { using (var xmlWriter = XmlWriter.Create(stringWriter)) { xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement(objectType.Name); IEnumerable<PropertyInfo> propertyInfos = objectType.GetProperties().OrderBy(r => r.Name); foreach (PropertyInfo propertyInfo in propertyInfos) { if (!propertyInfo.PropertyType.IsValueType && propertyInfo.PropertyType != typeof(string) || propertyInfo.PropertyType.IsEnum) continue; object newValue = propertyInfo.GetValue(newObj, null); var propertyInfo2 = oldObj.GetType().GetProperty(propertyInfo.Name); if (propertyInfo2 == null) continue; //todo: fix it in another way object oldValue = propertyInfo2.GetValue(oldObj, null); if (!ReflectionHelper.ValuesAreEqual(oldValue, newValue, propertyInfo.PropertyType.FullName)) { xmlWriter.WriteStartElement(propertyInfo.Name); xmlWriter.WriteElementString("Old", ConversionHelper.ObjToString(oldValue)); xmlWriter.WriteElementString("New", ConversionHelper.ObjToString(newValue)); xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); xmlWriter.WriteEndDocument(); } return stringWriter.ToString().RemoveXmlHeader(); } }
public static string GetObjectXml(object obj, string reason = null) { var objectType = obj.GetType(); using (var stringWriter = new Utf8StringWriter()) { using (var xmlWriter = XmlWriter.Create(stringWriter)) { xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement(objectType.Name); if (!string.IsNullOrEmpty(reason)) xmlWriter.WriteAttributeString("Reason", reason); IEnumerable<PropertyInfo> propertyInfos = objectType.GetProperties().OrderBy(r => r.Name); foreach(PropertyInfo propertyInfo in propertyInfos) { if (!propertyInfo.PropertyType.IsValueType && propertyInfo.PropertyType != typeof(string) || propertyInfo.PropertyType.IsEnum) continue; xmlWriter.WriteElementString(propertyInfo.Name, ConversionHelper.ObjToString(propertyInfo.GetValue(obj, null))); } xmlWriter.WriteEndElement(); xmlWriter.WriteEndDocument(); } return stringWriter.ToString().RemoveXmlHeader(); } }