Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using XmlSerializer with private and public const properties

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.

like image 588
Adam Haile Avatar asked Jan 09 '09 19:01

Adam Haile


4 Answers

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.

like image 76
Kent Boogaart Avatar answered Nov 15 '22 07:11

Kent Boogaart


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")]
like image 42
Thomas Levesque Avatar answered Nov 15 '22 08:11

Thomas Levesque


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.

like image 38
Hermit Avatar answered Nov 15 '22 08:11

Hermit


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.

like image 34
Marc Gravell Avatar answered Nov 15 '22 08:11

Marc Gravell