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