1

I'm using DataContractSerializer in my Web API application and in my action I'm returning a Data Type as below:

public class Event
{
  public string Name {get; set;}
  public IList<Division> Divisions {get;set;}
}

When serialized it's returning the below xml:

    <Event xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07
/EventTypeNameSpace">
        <Name>some name</Name>
        <Divisions i:nil="true" />
    </Event>

1) Why is it returning two xmlns:i and xmlns attributes? how can they be excluded?

2) How can I exclude the Divisions from the xml when it's null?

1 Answer 1

1

1: the "http://schemas.datacontract.org/2004/07" is the default namespace used by types serialized by data-contract serializer; if you don't like that - change your contract; the "http://www.w3.org/2001/XMLSchema-instance" defines "nil" as a special value

2: by defining the contract properly

[DataContract(Namespace="")]
public class Event
{
    [DataMember]
    public string Name { get; set; }

    [DataMember(EmitDefaultValue=false)]
    public IList<Division> Divisions { get; set; }
}

However: I should add - if you want tight control over what the layout looks like, you should probably be using XmlSerializer, not DataContractSerializer

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

1 Comment

thanks. The problem is that if I add DataMember, I'd have to add it for all other members that I liked to avoid but it seems not possible.

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.