Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add an XML attribute using DataContract

I have a simple class I'm serializing.

 [DataContract(Name = "Test", Namespace = "")]
 public class Test
 {
    [DataMember(Order = 0, Name = "Text")]
    public string Text { get; set; }

    public Test() {}
 }

This kicks out the following XML:

<Test>
   <Text>Text here</Text>
</Test>

What I want is:

<Test>
   <Text type="MyType">Text here</Text>
</Test>

How do I add attributes the the XML elements?

Thanks in advance.

like image 438
Magpie Avatar asked Oct 29 '09 14:10

Magpie


People also ask

What is Datacontract attribute?

[DataContract] attribute specifies the data, which is to serialize (in short conversion of structured data into some format like Binary, XML etc.) and deserialize(opposite of serialization) in order to exchange between the client and the Service.

What is Datacontract and Datamember?

A datacontract is a formal agreement between a client and service that abstractly describes the data to be exchanged. In WCF, the most common way of serialization is to make the type with the datacontract attribute and each member as datamember.

What is data contract serialization?

Data Contracts can be defined as follows: It describes the external format of data ed to and from service operations. It defines the structure and types of data exchanged in service messages. It maps a CLR type to an XML Schema. It defines how data types are serialized and deserialized.


2 Answers

You can't add attributes to a DataContract. You either have to use a class that Implements ISerializable or use the .Net XmlSerializer.

like image 182
Pete OHanlon Avatar answered Sep 18 '22 12:09

Pete OHanlon


Not exactly an answer, but you can try to implement IXmlSerializable to fully control output xml format.

like image 33
Nikolay R Avatar answered Sep 20 '22 12:09

Nikolay R