How do I add an XML attribute using DataContract

Magpie picture Magpie · Oct 29, 2009 · Viewed 28.5k times · Source

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.

Answer

Pete OHanlon picture Pete OHanlon · Oct 29, 2009

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