views:

597

answers:

3

Hi

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.

A: 

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

Nikolay R
+3  A: 

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

Pete OHanlon
A: 

Hi,

I think this could do the trick :

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

    [XmlAttribute("type")]
    public Type Type
    {
        get
        {
            return this.GetType();
        }
    }

    public Test() { }
}

Hope this helps, Regards.


EDIT: Forget this, things mixed up in my head and every synapses connections gone wrong there... (and anyway, I mixed DataContract and XML serialization attributes, and worst I was putting the attribute in the "Test" element instead of "Text" element). As other people said, with DataContract you will have to make your own serialization implementation with ISerializable

Ucodia
Quick poll: do you wish this did work?
alexdej
Of course, this case shows up how it could be helpful.
Ucodia