如何使用DataContract添加XML属性
我有一个简单的类我正在序列化。
[DataContract(Name = "Test", Namespace = "")] public class Test { [DataMember(Order = 0, Name = "Text")] public string Text { get; set; } public Test() {} }
这将推出以下XML:
Text here
我想要的是:
Text here
如何添加XML元素的属性?
提前致谢。
您无法向DataContract添加属性。 您必须使用Implements ISerializable的类或使用.Net XmlSerializer。
不完全是答案,但您可以尝试实现IXmlSerializable以完全控制输出xml格式。
我能够通过声明一个在其中定义属性的XElement来实现这一点。 例如:
public XElement Text { get; set;}
使用[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; } } }