views:

1048

answers:

6

What's the simplest way to get XmlSerializer to also serialize private and "public const" properties of a class or struct? Right not all it will output for me is things that are only public. Making it private or adding const is causing the values to not be serialized.

+3  A: 

XmlSerializer only looks at public fields and properties. If you need more control, you can implement IXmlSerializable and serialize whatever you would like. Of course, serializing a constant doesn't make much sense since you can't deserialize to a constant.

HTH, Kent

Kent Boogaart
+4  A: 

If you want to serialize/deserialize private members please see

http://stackoverflow.com/questions/420662/can-an-internal-setter-of-a-property-be-serialized

Andrew Hare
+1  A: 

Check out DataContractSerializer, introduced in .NET 3.0. It also uses XML format, and in many ways, it is better than XmlSerializer, including dealing with private data. See http://www.danrigsby.com/blog/index.php/2008/03/07/xmlserializer-vs-datacontractserializer-serialization-in-wcf/ for a full comparison.

If you only have .NET 2.0, there's the BinarySerializer that can deal with private data, but of course it's a binary format.

Roy Peled
A: 

Ok if you have to do that and also keep your fields still private, maybe you can;

private string myField;

public string MyField 
{
   get{ return MyField; }
   set { MyField = value; }
}
erdogany
+2  A: 

It doesn't make sense to consider const members, as they aren't per-instance; but if you just mean non-public instance members: consider DataContractSerializer (.NET 3.0) - this is similar to XmlSerializer, but can serialize non-public properties (although it is "opt in").

See here for more.

Marc Gravell
+1  A: 

Even though it's not possible to serialize private properties, you can serialize properties with an internal setter, like this one :

public string Foo { get; internal set; }

To do that, you need to pre-generate the serialization assembly with sgen.exe, and declare this assembly as friend :

[assembly:InternalsVisibleTo("MyAssembly.XmlSerializers")]
Thomas Levesque