static object DeserializeToCSharpObject_Object_WithRecursion(IEnumerable <XNode> content, Type resultType, XElement parentElement, IReadOnlyList <Type> knownTypes, bool ignoreErrors, bool useXmlSerializerFormat) { // Quit if attempting to deserialize to an interface: //todo: investigate why this may happen. if (!resultType.IsInterface) { string resultTypeFullName = resultType.FullName; // For debugging only, can be removed. // Create the resulting class: object resultInstance = Activator.CreateInstance(resultType); //todo: replace with "System.Runtime.Serialization.FormatterServices.GetUninitializedObject(type)" so that the type does not require a parameterless constructor. // Call the "OnDeserializing" method if any: CallOnDeserializingMethod(resultInstance, resultType); // Get the type information (namespace, etc.) by reading the DataContractAttribute and similar attributes, if present: TypeInformation typeInformation = DataContractSerializer_Helpers.GetTypeInformationByReadingAttributes(resultType, null); // Read the members of the target type: IEnumerable <MemberInformation> membersInformation = DataContractSerializer_Helpers.GetDataContractMembers(resultType, typeInformation.serializationType, useXmlSerializerFormat); // Make a dictionary of the members of the target type for faster lookup: Dictionary <string, MemberInformation> memberNameToMemberInformation = new Dictionary <string, MemberInformation>(); foreach (var memberInformation in membersInformation) { string memberName = memberInformation.Name; if (resultType.FullName.StartsWith("System.Collections.Generic.KeyValuePair")) { if (memberName == "key") { memberName = "Key"; } else if (memberName == "value") { memberName = "Value"; } } if (!memberNameToMemberInformation.ContainsKey(memberName)) { memberNameToMemberInformation.Add(memberName, memberInformation); } else { MemberInformation collidingMemberInformation = memberNameToMemberInformation[memberName]; throw new InvalidDataContractException( string.Format( "Type '{0}' contains two members '{1}' 'and '{2}' with the same data member name '{3}'. Multiple members with the same name in one type are not supported. Consider changing one of the member names using DataMemberAttribute attribute.", resultType.ToString(), memberInformation.MemberInfo.Name, collidingMemberInformation.MemberInfo.Name, memberName )); } } // Populate the values of the properties/members of the class: HashSet2 <string> membersForWhichWeSuccessfullSetTheValue = new HashSet2 <string>(); foreach (XNode node in content) { if (node is XElement) // Normally an object property was serialized as an XElement. { XElement xElement = (XElement)node; XName elementName = xElement.Name; string elementNameWithoutNamespace = elementName.LocalName; // Find the member that has the name of the XNode: MemberInformation memberInformation; if (memberNameToMemberInformation.TryGetValue(elementNameWithoutNamespace, out memberInformation)) { // Avoid processing nodes that have the same name as other nodes already processed (this can happen in case of [XmlElement] attribute on enumerable members - cf. "special case" below - but it is handled differently): if (!membersForWhichWeSuccessfullSetTheValue.Contains(memberInformation.Name)) { object memberValue = null; Type memberActualType = memberInformation.MemberType; // Note: this is the initial value. It may be modified below. if (DataContractSerializer_Helpers.IsElementNil(xElement)) { //---------------------- // XNode is "Nil", so we return the default value of the result type //---------------------- memberValue = DataContractSerializer_Helpers.GetDefault(memberInformation.MemberType); } else { bool isNull = false; //foreach (XAttribute attribute in xElement.Attributes(XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance").GetName("nil"))) //doesn't work... //todo: try removing this foreach since it should be handled in the "if(IsElementDefaut(xElement))" above. foreach (XAttribute attribute in xElement.Attributes("nil")) //We have to do this here because those usually do not have nodes, which causes problems when doing the recursion. { isNull = Convert.ToBoolean(attribute.Value); if (isNull) { memberValue = null; } } if (!isNull) { memberActualType = DataContractSerializer_KnownTypes.GetCSharpTypeForNode(xElement, memberInformation.MemberInfo.DeclaringType, memberActualType, knownTypes, memberInformation); //if the type is nullable, we get the undelying type: Type nonNullableMemberType = memberActualType; if (memberActualType.FullName.StartsWith("System.Nullable`1")) { nonNullableMemberType = Nullable.GetUnderlyingType(memberActualType); } // Recursively create the value for the property: IEnumerable <XNode> propertyChildNodes = xElement.Nodes(); //********** RECURSION ********** memberValue = DeserializeToCSharpObject(propertyChildNodes, nonNullableMemberType, xElement, knownTypes, ignoreErrors, useXmlSerializerFormat); } //--------------------------------- // Handle the special case where there is an [XmlElement] attribute on an enumerable member (XmlSerializer compatibility mode only): // // Example: // <MyObject> // <MyEnumerablePropertyName/> // <MyEnumerablePropertyName/> // <MyEnumerablePropertyName/> // </MyObject> // // obtained via: // class MyObject // { // [XmlElement] // List<MyType> MyEnumerablePropertyName { get; set; } // } // // cf. https://docs.microsoft.com/en-us/dotnet/standard/serialization/controlling-xml-serialization-using-attributes //--------------------------------- Type itemsType = null; bool specialCaseWhereAnEnumerableHasTheXmlElementAttribute = (useXmlSerializerFormat && memberInformation.HasXmlElementAttribute && DataContractSerializer_Helpers.IsAssignableToGenericEnumerableOrArray(memberActualType, out itemsType)); if (specialCaseWhereAnEnumerableHasTheXmlElementAttribute) { object deserializedEnumerable = DeserializeToCSharpObject_Enumerable_WithRecursion_SpecialCase( memberInformation.Name, content, memberActualType, knownTypes, ignoreErrors, itemsType, useXmlSerializerFormat); memberValue = deserializedEnumerable; } //--------------------------------- // Set the value of the member: //--------------------------------- DataContractSerializer_Helpers.SetMemberValue(resultInstance, memberInformation, memberValue); membersForWhichWeSuccessfullSetTheValue.Add(memberInformation.Name); } } } else { //----------- // We ignore missing members, to mimic the behavior of the .NET DataContractSerializer. //----------- //throw new Exception("Member '" + memberName + "' not found in type '" + resultType.Name + "'."); } } } // In case of XmlSerializer compatibility mode, and [XmlAttribute] attribute on a class member, we also need to deserialize the XAttributes (cf. https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlattributeattribute(v=vs.110).aspx ): if (useXmlSerializerFormat) { foreach (XAttribute attribute in parentElement.Attributes()) { XName attributeName = attribute.Name; // We assume that the object properties have no namespace //todo: fix this assumption, cf. "XmlAttributeAttribute.Namespace" for example (note: repetition of "Attribute" is intended) if (string.IsNullOrEmpty(attributeName.NamespaceName)) { string attributeNameWithoutNamespace = attributeName.LocalName; // Find the member that has the name of the XAttribute: MemberInformation memberInformation; if (memberNameToMemberInformation.TryGetValue(attributeNameWithoutNamespace, out memberInformation) && memberInformation.HasXmlAttributeAttribute) { // Avoid processing members that have already been processed (just in case): if (!membersForWhichWeSuccessfullSetTheValue.Contains(memberInformation.Name)) { string attributeValue = attribute.Value; // Check to see if the expected type is a value type: if (DataContractSerializer_ValueTypesHandler.TypesToNames.ContainsKey(memberInformation.MemberType)) { // Attempt to deserialize the string: object memberValue = DataContractSerializer_ValueTypesHandler.ConvertStringToValueType(attributeValue, memberInformation.MemberType); // Set the value of the member: DataContractSerializer_Helpers.SetMemberValue(resultInstance, memberInformation, memberValue); membersForWhichWeSuccessfullSetTheValue.Add(memberInformation.Name); } else { //todo: report the error? if (memberInformation.MemberType == typeof(List <int>)) { string[] splittedElements = attributeValue.Split(' '); #if !BRIDGE List <int> listint = splittedElements.Select(Int32.Parse).ToList(); #else List <int> listint = new List <int>(); foreach (string str in splittedElements) { listint.Add(Int32.Parse(str)); } #endif DataContractSerializer_Helpers.SetMemberValue(resultInstance, memberInformation, listint); membersForWhichWeSuccessfullSetTheValue.Add(memberInformation.Name); } } } else { //todo: report the error? } } else { //todo: report the error? } } } } // Verify that the values of all the members marked as "IsRequired" have been set: foreach (var memberInformation in membersInformation) { if (memberInformation.IsRequired && !membersForWhichWeSuccessfullSetTheValue.Contains(memberInformation.Name)) { throw new SerializationException(string.Format("The member '{0}' is required but it was not found in the document being deserialized.", memberInformation.Name)); } } // Call the "OnDeserialized" method if any: CallOnDeserializedMethod(resultInstance, resultType); return(resultInstance); } else { return(null); } }
internal static Type GetCSharpTypeForNode(XElement xElement, Type parentType, Type memberType, IReadOnlyList <Type> knownTypes, MemberInformation parentMemberInformationIfNotRoot, bool useXmlSerializerFormat) { // Look for the XML attribute named "type": XAttribute xmlTypeAttribute = null; foreach (XAttribute attribute in xElement.Attributes(XNamespace.Get(DataContractSerializer_Helpers.XMLSCHEMA_NAMESPACE).GetName("type"))) { xmlTypeAttribute = attribute; break; } //todo: if no "type" attribute was found, verify that the expected type ("memberType") has the same name and namespace of the XElement. If not, raise a SerializationException that says something like: Expecting element 'MainPage.Person' from namespace 'http://schemas.datacontract.org/2004/07/TestSilverlightDataContractSerializer1'. Encountered 'Element' with name 'MainPage.Person', namespace 'http://schemas.datacontract.org/2004/07/TestCshtml5DataContractSerializer1'. // If found, read it and process it: string typeNameInXmlTypeAttribute = null; string typeNamespaceInXmlTypeAttribute = null; if (xmlTypeAttribute != null) { GetNameAndNamespaceFromXmlTypeAttribute(xmlTypeAttribute, xElement, out typeNameInXmlTypeAttribute, out typeNamespaceInXmlTypeAttribute); } // If no type information was found, but the return type is "object", it means that we should consider the name of the XElement: if (string.IsNullOrWhiteSpace(typeNameInXmlTypeAttribute) && memberType == typeof(object)) { typeNameInXmlTypeAttribute = xElement.Name.LocalName; typeNamespaceInXmlTypeAttribute = (xElement.Name.Namespace != null ? xElement.Name.Namespace.NamespaceName : null); if (string.IsNullOrEmpty(typeNamespaceInXmlTypeAttribute)) { typeNamespaceInXmlTypeAttribute = xElement.GetDefaultNamespace().NamespaceName; } } // Look for a C# type that has the name and namespace specified by that "type" attribute: if (!string.IsNullOrWhiteSpace(typeNamespaceInXmlTypeAttribute) && !string.IsNullOrWhiteSpace(typeNameInXmlTypeAttribute)) { // Check if the type specified by the "type" attribute is the same as the expected member type: if (IsTypeSameAsTheOneSpecifiedInXmlTypeAttribute(memberType, typeNameInXmlTypeAttribute, typeNamespaceInXmlTypeAttribute, useXmlSerializerFormat)) { //---------------------------- // The actual type is same as the memberActualType. //---------------------------- // We found the type, so there is nothing to do. } // Check if the type specified by the "type" attribute is a built-in type: else if ((typeNamespaceInXmlTypeAttribute == DataContractSerializer_Helpers.XMLSCHEMA_NAMESPACE || typeNamespaceInXmlTypeAttribute == DataContractSerializer_Helpers.XMLSCHEMA_NAMESPACE_XSD || typeNamespaceInXmlTypeAttribute == DataContractSerializer_Helpers.XMLSCHEMA_NAMESPACE_TYPES) && DataContractSerializer_ValueTypesHandler.NamesToTypes.ContainsKey(typeNameInXmlTypeAttribute)) { //---------------------------- // It is a built-in type: //---------------------------- memberType = DataContractSerializer_ValueTypesHandler.NamesToTypes[typeNameInXmlTypeAttribute]; } // Look in the KnownTypes: else { //---------------------------- // We try to find the type with the specified name and namespace // by looking in the global known types, as well as the known // types of the parent type: //---------------------------- // First, look in the list of known types passed to the DataContractSerializer: bool typeWasFound = false; foreach (Type knownType in knownTypes) { if (IsTypeSameAsTheOneSpecifiedInXmlTypeAttribute(knownType, typeNameInXmlTypeAttribute, typeNamespaceInXmlTypeAttribute, useXmlSerializerFormat)) { memberType = knownType; typeWasFound = true; break; } } // If not found three, look in the [KnownType] attribute(s) of the parent type: if (!typeWasFound) { if (parentType != null) { foreach (Type knownType in GetKnownTypesByReadingKnownTypeAttributes(parentType)) { if (IsTypeSameAsTheOneSpecifiedInXmlTypeAttribute(knownType, typeNameInXmlTypeAttribute, typeNamespaceInXmlTypeAttribute, useXmlSerializerFormat)) { memberType = knownType; typeWasFound = true; break; } } } } if (!typeWasFound) { throw new SerializationException( string.Format( "Element '{0}' contains data of the '{1}' data contract. The deserializer has no knowledge of any type that maps to this contract. Add the type corresponding to '{2}' to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding it to the list of known types passed to DataContractSerializer.", parentMemberInformationIfNotRoot != null ? parentMemberInformationIfNotRoot.Name : "", typeNamespaceInXmlTypeAttribute + ":" + typeNameInXmlTypeAttribute, typeNameInXmlTypeAttribute )); } ////we try to get the type from the namespace and type name: //memberActualType = memberType.Assembly.GetType(ns + "." + typeName); } } return(memberType); }
public MemberInformationAndValue(MemberInformation memberInformation, object memberValue) { this.MemberInformation = memberInformation; this.MemberValue = memberValue; }