/// <summary> /// Deserializes xml into an object instance of the specified type. /// </summary> /// <param name="xml">The serialized xml of an instance of the specified type.</param> /// <returns>An instance of the specified type.</returns> /// <exception cref="ArgumentException"> /// Thrown when the xml is null or empty. /// </exception> public T Deserialize(string xml) { if (string.IsNullOrEmpty(xml)) { throw new ArgumentException(@"The xml string cannot be null or empty.", nameof(xml)); } var userObjectAttribute = typeof(T).GetCustomAttribute <UserObjectAttribute>(); if (userObjectAttribute == null) { throw MissingAttributeException.Create(typeof(T), typeof(UserObjectAttribute)); } string objectName = userObjectAttribute.ObjectName; var document = XDocument.Parse(xml); var xmlData = document.XPathSelectElement($@"//{objectName}"); var instance = new T(); var properties = GetSystemAndUserFields(); foreach (var property in properties) { SetProperty(property, xmlData, instance); } var children = GetChildrenProperties(); foreach (var child in children) { SetCollectionProperty(child, instance, document); } return(instance); }
public void MissingAttributeException_InitTest() { var expected_attributetype = new SqlColumnAttribute().GetType(); var missingAttributeException = new MissingAttributeException(expected_attributetype); var actual_attributeTypeExpected = missingAttributeException.AttributeTypeExpected; Assert.Equal(expected_attributetype, actual_attributeTypeExpected); }
public static string GetDescription <TEnum>(this TEnum enumValue) where TEnum : Enum { var attribute = enumValue.GetAttribute <TEnum, DescriptionAttribute>(); if (attribute is null) { throw MissingAttributeException.MissingFromField <DescriptionAttribute>(nameof(enumValue), typeof(TEnum)); } return(attribute.Description); }
/// <summary> /// Serializes the given instance. /// </summary> /// <returns> /// An XML representation of the object. /// </returns> public string Serialize(T instance) { var userObjectAttribute = typeof(T).GetCustomAttribute <UserObjectAttribute>(); if (userObjectAttribute == null) { throw MissingAttributeException.Create(typeof(T), typeof(UserObjectAttribute)); } var type = instance.GetType(); var xmlProperties = GetXmlProperties(instance); var childXmlProperties = GetChildXmlProperties(type, instance); var content = new XElement(userObjectAttribute.ObjectName, xmlProperties, childXmlProperties); var document = new XDocument(content); return(document.ToString(SaveOptions.DisableFormatting)); }