- Home /
Serialize XML to a string
I am trying to serialize a class into XML that can be stored to a string. I need this to be compatible with iOS, web browser, and flash, which means it can't use reflection to serialize. How can I do this? I need it to be put into a string because I will be sending it to a server, instead of saving anything locally (since the web browser doesn't allow for this).
Thanks for the help!
Answer by whydoidoit · Sep 28, 2012 at 09:10 PM
Firstly you are quite able to use reflection on iOS and web so long as on the web you don't do much fiddling with private fields.
You can use BinaryFormatter and Convert to create a string faster and smaller than XML.
Like this to create a compressed string:
var m = new MemoryStream();
var b = new BinaryFormatter();
b.Serialize(m, yourObject);
var s = Convert.ToBase64String(m.GetBuffer());
Like this to decompress it:
var m = new MemoryStream(Convert.FromBase64String(dataYouReceived));
var b = new BinaryFormatter();
var o = (YourObject)b.Deserialize(m);
You'll need System.IO and System.Runtime.Serialization.Binary
Awesome! That worked (after fixing a small error in your provided code, suppose to be m.GetBuffer(), and the Binary is in System.Runtime.Serialization.Formatters.Binary).
Quick question though... the string that is created from Convert.ToBase64String(b.GetBuffer()) isn't X$$anonymous$$L, but a compressed string?
Well BinaryFormatter makes a compressed byte array - Convert.ToBase64String() converts it to a string that can be sent via http.
(Oh, and by iOS, I meant iPad, which according to this http://answers.unity3d.com/questions/290690/why-is-my-ipad-crashing-when-i-try-to-user-xmlseri.html doesn't work)
Nah that's a load of rubbish on the reflection side. I know binary formatter works on IOS - I use it - and I also have a reflection based serializer Unity Serializer that makes use of a lot of reflection and works fine on everything.
Your answer
![](https://koobas.hobune.stream/wayback/20220613081622im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
C#-XMLSerialize a Struct with Vector3 Array in it 2 Answers
Mapping between classes for serialization 2 Answers
How to ignore EventHandler serialization? 1 Answer
Using BinaryFormatter for deserialization - ArgumentException: method argument length mismatch 0 Answers
whats the best way to save a large list of variables? 1 Answer