You can implement ISerializationSurrogate to either serialize non-serializable objects, or override serialization for classes you either can't extend or don't want to. You then add this surrogate to an ISurrogateSelector - for which SurrogateSelector in the BCL is a default implementation - and pass this to your formatter. An example is given below. Compile this, run it, and - if you'd like - open Example.bin to see your document serialized using a BinaryFormatter.
using System; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Xml; class SerializeXmlDocument // Pack it into our example serializable object. // Create a serialization surrogate to serialize the XmlDocument. // Create the surrogate selector. // Now serialize the object to a binary file. [Serializable] internal Tree(string name, XmlDocument doc) public string Name { get { return name; } } class XmlDocumentSerializer : ISerializationSurrogate internal XmlDocumentSerializer(string name) this.name = name; // Save the string to the SerializationInfo. public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) return null; |
For example:- Dim
// How to implement it....
end function
You really should be careful about serializing non-serializable objects, though. For some objects it's fine, but for other objects - like Windows Forms controls - you typically shouldn't. In the case of controls, they are tied to a Window handle that is valid only for your machine and only for that instance of your application. Attempting to deserialize the control on another machine or for another run of your application could simply fail or have disasterous results.
using System; using System.Xml; using System.Runtime.Serialization public class MyXmlDocument:XmlDocument,ISerializable { public MyXmlDocument():base(){} protected MyXmlDocument(SerializationInfo info, StreamingContext context) public virtual void GetObjectData(SerializationInfo info, StreamingContext context) |
Please comment this solution if you know a better way to do this job...
Is there any way to send the whole XmlDocument object byte by byte using the same channel?
Thank you very much!