How do I add an XML attribute using DataContract

2019-06-15 01:24发布

问题:

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.

回答1:

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



回答2:

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



回答3:

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

public XElement Text { get; set;}


回答4:

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; }
    }
}