views:

69

answers:

5

I'm currently using an XMLSerializer to serialize a list of a class of my own. One of the class's properties is an instance of a sealed class that does not have a parameterless constructor, so the XML Serializer refuses to serialize the class. How can I get around this? I need that property to be serialized.

Is there some way for me to specify how that class should be serialized?

We'd like to stay with XML; is there another XML serializer that I could use that would not have this problem?

Again, I apologize if this is a dupe, but I had no idea what to search.

[EDIT] To clarify, I don't have access to the source of the sealed class.

A: 

Can you make a private parameterless constructor? That will work assuming you have access to the class's code.

Steve Danner
Unfortunately, I don't have access to the source. It's part of an SDK.
NickAldwin
`XmlSerializer` won't look at private members
Tim Robinson
In that case, I would try Tim Robinson's idea. That was going to be my next suggestion :)
Steve Danner
+7  A: 

It's not possible to do directly; XmlSerializer can't cope with classes that don't have a parameterless constructor.

What I normally do is wrap the parameterless class in another class that's compatible with XML. The wrapper class has a parameterless constructor and a set of read-write properties; it has a FromXml method that calls the real class's constructor.

[XmlIgnore]
public SomeClass SomeProperty { get; set; }

[XmlElement("SomeProperty")]
public XmlSomeClass XmlSomeProperty
{
    get { return XmlSomeClass.ToXml(SomeProperty); }
    set { SomeProperty = value.FromXml(); }
}
Tim Robinson
That's a pretty cool way to do it, thanks!
NickAldwin
Simple and elegant.
Jesse C. Slicer
A: 

You can implement ISerializable on the containing class, then implement a custom serializer.

Dave Swersky
`ISerializable` is for `BinaryFormatter`. And even `IXmlSerializable` needs the ctor.
Marc Gravell
Ah. Didn't know about the binaryformatter. Couldn't you use a custom serializer and deserializer implementation to include property settings for the sealed object though?
Dave Swersky
@Dave - not with XmlSerializer, no. Unless you write it all from scratch.
Marc Gravell
A: 

Depending on the complexity of the xml, you might have some luck with DataContractSerializer. This doesn't offer anything like the same level of xml control, but it bypasses the constructor completely. And works for private types.

I might also ask: does it actually need to be xml? There are other serializers for things like json or protobuf that don't have the XmlSerializer limitations.

Marc Gravell
A: 

Use IXmlSerializable, XmlSerializer is too limited.

Max Toro