Replacing a XmlSerializer for a BinarySerializer. What should I know?
I've been using an XmlSerializer
all this time to serialize my Project
class to a file. It contains all sorts of information in it. Most stuff is done automatically by the XmlSerializer
, except for one or two classes that implement IXmlSerializable
. Now I want to switch to a 开发者_如何学编程binary serializer only to make the files smaller. I still don't want to serialize private fields or anything like that. I just want it to behave exactly as an XmlSerializer but to generate smaller files.
Is there any easy way to do this, or will I have to make lots of changes to my application? Or, is there any other kind of serializer I should be using instead?
Switching to BinaryFormatter
is a bad idea here, IMO - it radically changes the behaviour and in particular your ability to trust the files between versions and between platforms. It also means you are now serializing your fields, which may not be a 1:1 map to the data you wanted to serialize (the public members, by default).
If you want smaller, perhaps just run it through DeflateStream
or GZipStream
. If that isn't enough, my next move would be to switch to something like protobuf-net, for the reason that it behaves very similarly (not identically) to XmlSerializer
, but as a binary serializer (not a field serializer). However, it does not respect IXmlSerializable
- depending on the complexity, that may be easy to side-step.
IMHO, the easiest solution to make your files smaller is to go the way the current Office XML formats (ODF and the one from MS) go: Zip it. This way, you don't have to change anything in your classes.
If you do it only for space, might compressing the XML files after serialization be an alternative? This way you would keep readability and you could name your files project.xml.zip
.
精彩评论