How do I add an XML attribute using DataContract
Asked Answered
G

4

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.

Grinder answered 29/10, 2009 at 14:10 Comment(0)
L
15

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

Lovell answered 29/10, 2009 at 14:14 Comment(1)
Depending on the system doing the serialization, it is possible to do what the OP is asking - see: #4859298Unnatural
I
2

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

Impressure answered 29/10, 2009 at 14:12 Comment(0)
W
1

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

public XElement Text { get; set;}
Wakerife answered 16/6, 2013 at 16:2 Comment(1)
The code [DataMember(Name = "test")] public XElement test = new XElement("Root", new List<string>() { "1", "2", "3" }); yields <test> <Root xmlns="">123</Root> </test> which is probably not what the quenstioner has intendedForensic
S
-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; }
    }
}
Spate answered 17/3, 2014 at 14:58 Comment(1)
I tried that and did not get Text nor type serializedForensic

© 2022 - 2024 — McMap. All rights reserved.