0

I tried using advice from other articles here on StackOverflow regarding this issue, but no dice. I am unable to suppress my null properties from Xml Serialization.

Here's my fairly simple class. As you can see I am trying to use declarative attributes, as well as the ShouldSerialize{variable} technique but neither of these is effective in suppressing these from the Xml.

public class Practice
{
#pragma warning disable 0649
    public int id;
    public string name;
    public string sharedId;
    public string sharedIdType;
    
    [XmlElement(IsNullable = false)]
    public List<Doctor> doctors;

    [XmlElement(IsNullable = false)]
    public List<Employee> employees;

    public bool ShouldSerializedoctors()
    {
        return !(doctors == null);
    }

    public bool ShouldSerializeemployees()
    {
        return !(employees == null);
    }
#pragma warning restore 0649
}

Here is a snippet from the the resulting Xml. As you can see, doctors was serialized into the Xml even though it is null. This is a WebAPI project running on Framework 4.5.2. Any idea what I'm doing wrong?

<ArrayOfPractice xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/rater8.Common.Models">
   <Practice>
       <doctors i:nil="true"/>
       <employees>
           <Employee>
              <id>49</id>

BTW - I was able to suppress the null values from Json serialization using:

config.Formatters.JsonFormatter.SerializerSettings =
    new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };

Here is some additional information:

By adding the following statement into WebApiCofig.Register I now see the suppression of the nil elements.

config.Formatters.XmlFormatter.UseXmlSerializer = true;

Here is the full code for this method:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.Formatters.JsonFormatter.SerializerSettings =
             new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };

        config.Formatters.XmlFormatter.UseXmlSerializer = true;

        GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add
            (new QueryStringMapping("format", "json", "application/json"));
        GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add
            (new QueryStringMapping("format", "xml", "application/xml"));
    }
}

So this solves the original problem description but this raises some additional questions.

  1. What is the default WebAPI Xml Serializer, other than XmlSerializer?

  2. I note that the structure of the Xml emitted by XmlSerializer is different (aside from the omission of the nil elements) than that which is emitted by the default WebAPI serializer. Is this going to cause problems on the attempt to deserialize the Xml to its class representation at the receiving end?

2
  • I wasn't capable of reproducing your problem. Can you share a small project showing how you are proceeding? Commented Jun 4, 2021 at 13:49
  • The problem goes away if I explicitly use XmlSerializer. (config.Formatters.XmlFormatter.UseXmlSerializer = true;) Commented Jun 4, 2021 at 16:59

2 Answers 2

1

add in class

[Serializable]
[DataContract(IsReference = true)]

add in fields

[DataMember]

and add config

config.Formatters.XmlFormatter.UseXmlSerializer = true;

AND remove

[XmlElement(IsNullable = false)] 

in fields

Sign up to request clarification or add additional context in comments.

Comments

0

This declarative tag - [XmlElement(IsNullable = false)] - is honored by the XmlSerializer, but ignored by the DataContractSerializer. If you want to use this tag you need to explicitly select the XmlSerializer. As follows:

public static class WebApiConfig
{
   public static void Register(HttpConfiguration config)
   {
       // Web API configuration and services

       ...

       config.Formatters.XmlFormatter.UseXmlSerializer = true;

       ...

   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.