Reputation: 1068
I am trying to serialize my object to xml. A serializer seemingly serializes all data members as children, but I want to serialize all members as attributes, not children.
Here's a code example:
[DataContract]
public class MyDataClass
{
[DataMember]
int foo = 24;
[DataMember]
string bar = "brabrabra";
}
This will be serialized as following xml when I use DataContractSerializer:
<MyDataClass xmlns="..." xmlns:i="...">
<foo>24</foo>
<bar>brabrabra</bar>
</MyDataClass>
However, I want to serialize it as following xml somehow:
<MyDataClass xmlns="..." xmlns:i="..." foo="24" bar="brabrabra" />
Is there any way to serialize like that? Or, should I write my own serializer to realize it? For reference, I am using DataContract serializer in this sample, but I can change it to a normal XmlSerializer or another one if there's a better one.
Hope someone knows about this.
Aki
Upvotes: 2
Views: 1241
Reputation: 7896
You can use a simple XmlSerializer to achieve this, in the following way:
[Serializable]
public class SerializationTest2
{
[XmlAttributeAttribute]
public string MemberA { get; set; }
}
[Test]
public void TestSerialization()
{
var d2 = new SerializationTest2();
d2.MemberA = "test";
new XmlSerializer(typeof(SerializationTest2))
.Serialize(File.OpenWrite(@"c:\temp\ser2.xml"), d2);
}
Upvotes: 2
Reputation: 19956
Put [XmlAttribute]
before foo
and bar
declaration.
Great ref: http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx
Upvotes: 0
Reputation: 5658
Have a look at XMLAttribute. Only works with XMLSerializer though.
Upvotes: 3