开发者

How do I add an XML attribute using DataContract

开发者 https://www.devze.com 2022-12-09 23:11 出处:网络
I have a simple class I\'m serializing. [DataContract(Name = \"Test\", Namespace = \"\")] public class Test

I have a simple class I'm serializing.

 [DataContract(Name = "Test", Namespace = "")]
 public class Test
 {
    [DataMember(Order = 0, Name = "Text")]
    public string Text { get; s开发者_JAVA百科et; }

    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.


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


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


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

public XElement Text { get; set;}


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

精彩评论

暂无评论...
验证码 换一张
取 消