1

Given a business object 'Order', how can I implement a DataContract attribute so that the Order object serializes to this:

<Order xmlns="http://schemas.datacontract.org/2004/07/appulsive.MyCompany.SomeWebService"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
...etc.
</Order>

There appears to be a default namespace as well as a specific one. I have been told this is a requirement to work with the web service in question.

TIA.

1 Answer 1

0

Assuming you are using DataContractSerializer, you just need to add [DataContract(Name="desired name", Namespace="desired namespace")] to the class:

[DataContract(Name = "Order", Namespace = "http://schemas.datacontract.org/2004/07/appulsive.MyCompany.SomeWebService")]
public class Order
{
    /// Various data members
    [DataMember]
    public string SomeStuff { get; set; }
}

Having done so, you also need to mark all properties you wish to serialize with [DataMember] since data contract serialization is opt-in. Then the XML generated by DataContractSerializer will look like:

<Order xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/appulsive.MyCompany.SomeWebService">
    <SomeStuff>some stuff</SomeStuff>
</Order>

As you can see, the namespace "http://www.w3.org/2001/XMLSchema-instance" is automatically included. That's because it is a standard namespace that contains definitions for standard attributes including nil (representing a null value) and type (holding type information for a polymorphic type). Since these attributes are almost always required, it's conventional to add the namespace to the root element, and in fact DataContractSerializer does so.

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

2 Comments

Okay, so I DON'T need to specify the default namespace, only the specific one, in order for both to be included in the XML? Is that correct?
@NeilHaughton - you need to specify the namespace that Order is in, which becomes the default namespace. The i:... namespace is a standard namespace that is auto-included.

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.