17

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.

Magpie
  • 6,983
  • 14
  • 51
  • 67

4 Answers4

15

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
  • 9,086
  • 2
  • 29
  • 28
  • 5
    Depending on the system doing the serialization, it is possible to do what the OP is asking - see: http://stackoverflow.com/questions/4858798/datacontract-xml-serialization-and-xml-attributes/4859084#4859084 – jeffreypriebe Oct 23 '11 at 01:32
2

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

Nikolay R
  • 957
  • 2
  • 11
  • 22
1

I was able to achieve this by declaring an XElement which has attributes defined in it. Ex:

public XElement Text { get; set;}
guiomie
  • 4,988
  • 6
  • 37
  • 67
  • 2
    The code `[DataMember(Name = "test")] public XElement test = new XElement("Root", new List() { "1", "2", "3" });` yields ` 123 ` which is probably not what the quenstioner has intended – codingdave Oct 21 '14 at 11:02
-3

Add the type attribute with [XMLAttribute] and the element value with [XmlText].

public class Test
{
    public text Text;

    public Test()
    {
        Text = new text();
    }

    [DataContract(Name = "Test", Namespace = "")]
    public class text
    {
        [XmlText]
        public string Text { get; set; }
        [XmlAttribute]
        public string type { get; set; }
    }
}