How to XML-serialize a sealed class without a constructor without parameters?

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

Is there a way to indicate how this class should be serialized?

We would like to stay with XML; Is there another XML serializer that I could use that doesn't have this problem?

Again, I apologize if this is a hoax, but I had no idea what to look for.

[EDIT] To clarify, I do not have access to the source of the private class.

+4
source share
5 answers

This cannot be done directly; XmlSerializer cannot handle classes that don't have a constructor without parameters.

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

 [XmlIgnore] public SomeClass SomeProperty { get; set; } [XmlElement("SomeProperty")] public XmlSomeClass XmlSomeProperty { get { return XmlSomeClass.ToXml(SomeProperty); } set { SomeProperty = value.FromXml(); } } 
+11
source

Can you create a private constructor without parameters? This will work if you have access to the class code.

0
source

You can implement ISerializable in the containing class, and then implement your own serializer.

0
source

Depending on the complexity of the xml, you might be lucky with the DataContractSerializer . This does not offer anything like the xml control level, but completely bypasses the constructor. And it works for private types.

I can also ask: should it really be xml? There are other serializers for things like json or protobuf that do not have XmlSerializer restrictions.

0
source

Use IXmlSerializable , XmlSerializer too small.

0
source

All Articles