views:

285

answers:

4

Consider a simple case

public class Test {
  public String myString;
}

Is there any way I can tell XmlSerializer to base64 encode myString when serializing it ?

+2  A: 

You store the string as a Base64 value, and then have a property which decodes it in the get clause.

Yuriy Faktorovich
+1, though I'd do it the other way round (store plain, have a property which encodes/decodes it just for serialization, provided that serialization is less used than just accessing the string).
OregonGhost
A: 

The only supported way to change the output from the XmlSerializer class (without ugly hacks like having special hidden properties etc) is to implement the IXmlSerializable interface.

You could save yourself having to write serialization code for the whole class by defining a Base64String class that implements IXmlSerializable and just writes out the encoded string. Define an operator to make it implicitly castable to a string and it should work pretty much like a normal string does.

Jon Grant
+4  A: 

Base64 converts binary data into a string. If you want to base64 encode the data in a string, you'd need to encode it in byte array first, e.g. using Encoding.UTF.GetBytes(myString).

This raises the question of why exactly you'd want to do this in the first place. If you need to use base 64, are you sure that you've really got text data to start with?

Jon Skeet
+2  A: 

You can simply set it to be a byte[] property and it will Base64 encode it automatically:

public class Test {
  public byte[] MyProperty {get;set;}

  public void SetMyProperty(string text)
  {
      MyProperty = System.Text.Encoding.Unicode.GetBytes(text);
  }
}

Test test = new Test();
test. SetMyProperty("123456789123456789");

Output:

<MyProperty>MQAyADMANAA1ADYANwA4ADkAMQAyADMANAA1ADYANwA4ADkA</MyProperty>

(Try decoding that here)

Unfortunately there is no way (that I know of) to make MyProperty private and still be serialized in System.Xml.Serialization.

Chris S