bavaza
bavaza

Reputation: 11047

Serialize an object to XML without using attributes

Is it possible to control XmlSerializer/DataContractSerializer behavior without specifying any serialization attributes?

To be more specific, I want to control the serialization (XmlIgnore, custom attribute name etc.), but without decorating my properties. Use cases:

For example, how would I serialize the following without uncommenting the attributes:

// [Serializable]
public MyClass
{
    // [XmlIgnore] - The following property should not be serialized, without uncommenting this line
    public int DontSerializeMeEvenThoughImPublic { get; set; }

    // [XmlAttribute("another_name")] - should be serialized as 'another_name', not 'SerializeMeAsXmlAttribute'
    public double SerializeMeAsXmlAttribute { get; set; }

    // [DataMember] - should be included
    private string IWantToBeSerializedButDontDecorateMeWithDataMember { get; set; }
}

Upvotes: 3

Views: 4072

Answers (3)

Jens
Jens

Reputation: 3412

I know this is an old question, but for the XmlSerializer part, it's interesting that no one has suggested the use of Attribute overrides.

Although not solving the Private property, but AFAIK you can't do that with attributes either, so the only route there would be the IXmlSerializable interface.

But what you can do by adding Attributes should be possible with overrides as well.

The following should work for the change wishes reflected by the outcommented XmlAttributes:

public class Program
{
    public static void Main()
    {
        XmlAttributeOverrides overrides = new XmlAttributeOverrides();
        overrides.Add(typeof(MyClass), "DontSerializeMeEvenThoughImPublic", new XmlAttributes { XmlIgnore = true });
        overrides.Add(typeof(MyClass), "SerializeMeAsXmlAttribute", new XmlAttributes { XmlAttribute = new XmlAttributeAttribute("another_name") });
        XmlSerializer serializer = new XmlSerializer(typeof(MyClass), overrides);
        using (var writer = new StringWriter())
        {
            serializer.Serialize(writer, new MyClass());
            Console.WriteLine(writer.ToString());
        }
    }
}

Upvotes: 4

Eli Algranti
Eli Algranti

Reputation: 9007

You can't (do it elegantly).
The only way to modify the way the XmlSerializer serializes classes is by using attributes (by the way SerializableAttribute is not required). The DataContractSerializer is even worse.

One possible solution is to create intermediate classes for XML serialization/desrialization and use Automapper to copy the data between the "real" class and mediator. I've used this approach to keep the front end XML serialization concerns outside of my business logic data types.

Upvotes: 5

Codor
Codor

Reputation: 17605

Serialization via XmlSerializer should work without the attributes.

Upvotes: 2

Related Questions