[ACCEPTED]-Using XmlSerializer with private and public const properties-xml-serialization
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.
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 :
[assembly:InternalsVisibleTo("MyAssembly.XmlSerializers")]
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.
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.
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.
Here's my solution to putting immutable 2 values in a property that will serialize 1 to XML:
[XmlElement]
public string format { get { return "Acme Order Detail XML v3.4.5"; } set { } }
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.