Using XmlSerializer with private and public const properties

前端 未结 6 2062
渐次进展
渐次进展 2020-12-19 08:07

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

相关标签:
6条回答
  • 2020-12-19 08:52

    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.

    0 讨论(0)
  • 2020-12-19 08:52

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

    [XmlElement]
    public string format { get { return "Acme Order Detail XML v3.4.5"; } set { } }
    
    0 讨论(0)
  • 2020-12-19 08:54

    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 one has unfortunately detour via json.

    0 讨论(0)
  • 2020-12-19 09:00

    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.

    0 讨论(0)
  • 2020-12-19 09:09

    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.

    0 讨论(0)
  • 2020-12-19 09:14

    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")]
    
    0 讨论(0)
提交回复
热议问题