如何使用DataContract添加XML属性
我有一个简单的类,我正在序列化。如何使用DataContract添加XML属性
[DataContract(Name = "Test", Namespace = "")]
public class Test
{
[DataMember(Order = 0, Name = "Text")]
public string Text { get; set; }
public Test() {}
}
这踢了以下XML:
<Test>
<Text>Text here</Text>
</Test>
我要的是:
<Test>
<Text type="MyType">Text here</Text>
</Test>
如何添加属性的XML元素?
在此先感谢。
您不能将属性添加到DataContract。您必须使用实现ISerializable的类或使用.Net XmlSerializer。
不完全是答案,但您可以尝试实现IXmlSerializable以完全控制输出xml格式。
我可以通过声明一个XElement来实现这个功能,该XElement具有在其中定义的属性。例如:
public XElement Text { get; set;}
代码 '[DataMember(Name =“test”)] public XElement test = new XElement(“Root”,new List
用[XMLAttribute]添加type属性,并用[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; }
}
}
我试过了,并没有得到文本NOR型系列化 – codingdave 2014-10-21 10:51:23
'IXmlSerializable' for xml。 – 2011-01-19 22:51:09
根据系统进行序列化,可以做OP所要求的 - 参见:http://stackoverflow.com/questions/4858798/datacontract-xml-serialization-and-xml-attributes/4859084#4859084 – jeffreypriebe 2011-10-23 01:32:45