简体   繁体   中英

How to specify multiple namespaces in DataContract attribute

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM