[ACCEPTED]-Using XmlSerializer with private and public const properties-xml-serialization

Accepted answer
Score: 17

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

Score: 10

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

public string Foo { get; internal set; }

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

Score: 4

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

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

Score: 2

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

See here for more.

Score: 0

One other solution the use of Newtonsoft.Json:

   var json = Newtonsoft.Json.JsonConvert.SerializeObject(new { root = result });
   var xml = (XmlDocument)Newtonsoft.Json.JsonConvert.DeserializeXmlNode(json);

Sure, this 1 one has unfortunately detour via json.

Score: 0

Here's my solution to putting immutable 2 values in a property that will serialize 1 to XML:

public string format { get { return "Acme Order Detail XML v3.4.5"; } set { } }

More Related questions