How do I add an XML attribute using DataContract

喜欢而已 提交于 2019-12-08 14:46:08

问题


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


来源:https://stackoverflow.com/questions/1644004/how-do-i-add-an-xml-attribute-using-datacontract

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!