Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8656739
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T15:21:13+00:00 2026-06-12T15:21:13+00:00

I have read many posts regarding deserialization of nullable fields but have not run

  • 0

I have read many posts regarding deserialization of nullable fields but have not run across the following scenario:

  1. Serialize an object with a nullable field that contains a value (“nil” attribute is not added to the node because it contains a value).
  2. Remove the value from the nullable field in the xml (this happens via client-side processing).
  3. Deserialize the xml.

Step 3 throws an error because the serializer does not treat the empty value of the nullable field as a null value (because “nil=true” is not specified). It instead tries to convert the value to the field’s data type (ex: Guid), which fails resulting in an error message that varies depending on the field’s data type.

In the case of a Guid the error message is:

    System.InvalidOperationException: There is an error in XML document ([line number], [column number]). ---> System.FormatException: Unrecognized Guid format.

I should note that the serialization / deserialization methods we use are framework methods that use generics.

I’m looking for an elegant and generic solution. The only feasible, generic solution I can think of is the following:

  1. Convert the xml to an XDocument.
  2. Use (less than desired) reflection to get all of the properties of the object that are reference types.
  3. Add “nil=true” attribute to all nodes whose name is found in the list from #2 and has an empty value.
  4. Use recursion to process each reference type in #2.

Note: Simply adding “nil=true” to all nodes that have an empty value will not work because the serializer will throw an error for value types that cannot be null.

[Edit] Code examples:

Sample data class

    public class DummyData
    {
        public Guid? NullableGuid { get; set; }
    }

Xml sent to client

    <DummyData>
    <NullableGuid>052ec82c-7322-4745-9ac1-20cc4e0f142d</NullableGuid>
    </DummyData>

Xml returned from client (error)

    <DummyData>
    <NullableGuid></NullableGuid>
    </DummyData>

Xml returned from client (desired result)

    <DummyData>
        <NullableGuid p2:nil="true" xmlns:p2="http://www.w3.org/2001/XMLSchema-instance"></NullableGuid>
    </DummyData>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T15:21:14+00:00Added an answer on June 12, 2026 at 3:21 pm

    Here is the solution I came up with that pretty closely resembles my plan of attack described in the original question.

    Disclaimer: It is not short and most likely does not cover every deserialization scenario but seems to get the job done.

        public static T FromXml<T>(string xml)
        {
           string convertedXml = AddNilAttributesToNullableTypesWithNullValues(typeof(T), xml);
           var reader = new StringReader(convertedXml);
           var serializer = new XmlSerializer(typeof (T));
           var data = (T) serializer.Deserialize(reader);
           reader.Close();
           return data;
        }
    
        private static string AddNilAttributesToNullableTypesWithNullValues(Type type, string xml)
        {
            string result;
    
            if (!string.IsNullOrWhiteSpace(xml))
            {
                XDocument doc = XDocument.Parse(xml);
    
                if (doc.Root != null)
                    AddNilAttributesToNullableTypesWithNullValues(doc.Root, type);
    
                result = doc.ToString();
            }
            else
                result = xml;
    
            return result;
        }
    
        private static void AddNilAttributesToNullableTypesWithNullValues(XElement element, Type type)
          {
             if (type == null)
                throw new ArgumentNullException("type");
    
             if (element == null)
                throw new ArgumentNullException("element");
    
             //If this type can be null and it does not have a value, add or update nil attribute
             //with a value of true.
             if (IsReferenceOrNullableType(type) && string.IsNullOrEmpty(element.Value))
             {
                XAttribute existingNilAttribute = element.Attributes().FirstOrDefault(a => a.Name.LocalName == NIL_ATTRIBUTE_NAME);
    
                if (existingNilAttribute == null)
                   element.Add(NilAttribute);
                else
                   existingNilAttribute.SetValue(true);
             }
             else
             {
                //Process all of the objects' properties that have a corresponding child element.
                foreach (PropertyInfo property in type.GetProperties())
                {
                   string elementName = GetElementNameByPropertyInfo(property);
    
                   foreach (XElement childElement in element.Elements().Where(e =>
                      e.Name.LocalName.Equals(elementName)))
                   {
                      AddNilAttributesToNullableTypesWithNullValues(childElement, property.PropertyType);
                   }
                }
    
                //For generic IEnumerable types that have elements that correspond to the enumerated type,
                //process the each element.
                if (IsGenericEnumerable(type))
                {
                   Type enumeratedType = GetEnumeratedType(type);
    
                   if (enumeratedType != null)
                   {
                      IEnumerable<XElement> enumeratedElements = element.Elements().Where(e =>
                         e.Name.LocalName.Equals(enumeratedType.Name));
    
                      foreach (XElement enumerableElement in enumeratedElements)
                         AddNilAttributesToNullableTypesWithNullValues(enumerableElement, enumeratedType);
                   }
                }
             }
          }
    
          private static string GetElementNameByPropertyInfo(PropertyInfo property)
          {
             string overrideElementName = property.GetCustomAttributes(true).OfType<XmlElementAttribute>().Select(xmlElementAttribute => 
                xmlElementAttribute.ElementName).FirstOrDefault();
             return overrideElementName ?? property.Name;
          }
    
          private static Type GetEnumeratedType(Type type)
          {
             Type enumerableType = null;
    
             Type[] types = type.GetGenericArguments();
    
             if (types.Length == 1)
                enumerableType = types[0];
    
             return enumerableType;
          }
    
          public static bool IsGenericEnumerable(Type type)
          {
             return type.IsGenericType && type.GetInterfaces().Any(i => 
                i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEnumerable<>));
          }
    
          private static bool IsReferenceOrNullableType(Type type)
          {
             return !type.IsValueType || Nullable.GetUnderlyingType(type) != null;
          }
    
          private const string NIL_ATTRIBUTE_NAME = "nil";
          private const string XML_SCHEMA_NAMESPACE = "http://www.w3.org/2001/XMLSchema-instance";
    
          private static XAttribute NilAttribute
          {
             get
             {
                 if (_nilAttribute == null)
                 {
                     XNamespace xmlSchemaNamespace = XNamespace.Get(XML_SCHEMA_NAMESPACE);
                     _nilAttribute = new XAttribute(xmlSchemaNamespace + NIL_ATTRIBUTE_NAME, true);
             }
    
            return _nilAttribute;
         }
      }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

i have read many posts but can not find my answer.my question is a
I have read many posts regarding detection of popup blocker by javascript code but
I have read many posts about this now but I do not still understand
I have read many questions about the facebook login but until not I didnt
OK I have read many posts regarding Dual Licensing using MIT and GPL licenses.
I have read in many posts that global variables are bad, but I need
I have read many posts(problems) with IE and jquery posts, but never thought I'd
I have read many posts on Session-scoped data in MVC, but I am still
I have read many posts on SO and the web regarding the keywords in
I know there have been many posts regarding array sorting, but I have looked

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.