tags:

views:

75

answers:

3

Hi All,

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

+2  A: 

Have a look at XMLAttribute. Only works with XMLSerializer though.

testalino
Thank you for your help. =)
Aki24x
A: 

Put [XmlAttribute] before foo and bar declaration.

Great ref: http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx

Daniel Mošmondor
Thank you for your quick answer and the reference. =)
Aki24x
A: 

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);
}
Ioannis Karadimas
Perfect! Thank for your exact answer. =D
Aki24x