Using XmlSerializer with private and public const properties

What is the easiest way to force the XmlSerializer to also serialize the private and "public const" properties of a class or structure? The right is not all that he will deduce for me, these are things that are only public. Creating it private or adding const causes the values ​​to not be serialized.

+6
c # xml-serialization
source share
6 answers

XmlSerializer considers only open fields and properties. If you need more control, you can implement IXmlSerializable and serialize whatever you want. Of course, serializing a constant does not make much sense, since you cannot deserialize a constant.

+15
source share

Even if it is not possible to serialize private properties, you can serialize properties using an internal setter, for example:

 public string Foo { get; internal set; } 

To do this, you need to pre-generate the serializing assembly using sgen.exe and declare this assembly as a friend:

 [assembly:InternalsVisibleTo("MyAssembly.XmlSerializers")] 
+9
source share

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

If you have only .NET 2.0, there is a BinarySerializer that can handle private data, but, of course, this is a binary format.

+3
source share

It makes no sense to consider const members, since they are not instances; but if you just mean non-public instance members: consider a DataContractSerializer (.NET 3.0) - this is similar to the XmlSerializer , but it can serialize non-public properties (although this is a "select").

See more details.

+2
source share

Another solution is to use Newtonsoft.Json:

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

Of course, this one unfortunately bypasses through json.

0
source share

Here is my decision to put immutable values ​​in a property that will be serialized in XML:

 [XmlElement] public string format { get { return "Acme Order Detail XML v3.4.5"; } set { } } 
0
source share

All Articles