myWorld
myWorld

Reputation: 49

Why is XML serialzation suggested over SOAP and binary serialzation?

I'm trying to serialize a string with some escape characters (\0). But when I deserialise it throws an exception.

//XML serialization

    private static void M1()
        {
            string str = "\0AC";

           StringWriter sw = new StringWriter();
            XmlSerializer serializer = new XmlSerializer(typeof(String));
            serializer.Serialize(sw, str);
            System.Console.WriteLine("String encoded to XML = \n{0} \n", sw.ToString());
            StringReader sr = new StringReader(sw.ToString());
            String s2 = (String)serializer.Deserialize(sr);

            System.Console.WriteLine("String decoded from XML = \n {0}", s2);
        }

//Using Binary serialization

    void BinaryFormat1()
     {
         IFormatter bf = new BinaryFormatter();
         string str = "\0MyName";
         FileStream fs = new FileStream("SerilizedString.Data", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
         bf.Serialize(fs, str);
         fs.Close();
         fs = new FileStream("SerilizedString.Data", FileMode.Open, FileAccess.Read, FileShare.None);
         string data = (string)bf.Deserialize(fs);
         fs.Close();
         Console.WriteLine("data : " + data.ToString());
     }

Upvotes: 1

Views: 160

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499770

I'd expect SOAP to have the same problem, to be honest. It's the issue of not being able to represent every Unicode string in "standard" XML.

That leaves binary serialization, which:

  • Will only work with .NET (so is bad for interoperability)
  • Isn't human readable (or easily translated into a human readable form if you run into problems)
  • Is hard to work with in terms of versioning

Personally I prefer custom serialization options such as Thrift or Protocol Buffers, but as the author of a Protocol Buffers port to C#, I'm biased :)

Upvotes: 3

Related Questions