private static void FromXml(object targetObject, XDocument document, XmlSerializationDefinition definition)
        {
            targetObject.ThrowIfNull(nameof(targetObject));
            document.ThrowIfNull(nameof(document));
            definition.ThrowIfNull(nameof(definition));

            if (document.Root != null)
            {
                Serializer.Deserialize(targetObject, document.Root, definition);
            }
        }
        private static object FromXml(Type targetType, XDocument document, XmlSerializationDefinition definition)
        {
            targetType.ThrowIfNull(nameof(targetType));
            document.ThrowIfNull(nameof(document));
            definition.ThrowIfNull(nameof(definition));

            // If the root element is null, then don't bother and return the default type.
            if (document.Root == null)
            {
                return(SerializationUtilities.GetDefaultValue(targetType));
            }

            return(Serializer.Deserialize(targetType, document.Root, definition));
        }
        private static XDocument ToXml(object objectToSerialize, XmlSerializationDefinition definition)
        {
            definition.ThrowIfNull(nameof(objectToSerialize));

            // If it's already a document, then don't bother.
            if ((objectToSerialize != null) && objectToSerialize is XDocument)
            {
                return(objectToSerialize as XDocument);
            }

            // Create the document and add a declaration, if any.
            XDocument document = new XDocument();

            // Create the root element, if any.
            if (objectToSerialize != null)
            {
                // The type should define an XML root attribute.
                Type objectType             = objectToSerialize.GetType();
                XmlObjectAttribute rootInfo = Attribute.GetCustomAttribute(objectType, typeof(XmlObjectAttribute), false) as XmlObjectAttribute;
                if (rootInfo == null)
                {
                    throw new XmlException("The object to serialize of type {0} has not defined an {1} attribute.", objectType.Name, typeof(XmlObjectAttribute).Name);
                }

                // Serialize the object and define the name of the root element.
                XElement rootElement = Serializer.Serialize <XElement>(objectToSerialize, definition);
                if (rootElement != null)
                {
                    rootElement.Name = !string.IsNullOrEmpty(rootInfo.RootName) ? rootInfo.RootName : objectType.Name;
                    rootElement.Add(new XAttribute(XNamespace.Xmlns + XmlSerializationDefinition.XmlSchemaPrefix, XmlSerializationDefinition.XmlSchemaURL));
                }
                document.Add(rootElement);
            }

            return(document);
        }