Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>From the description I assume you are using <code>XmlSerializer</code>. The fact is that <code>XmlSerializer</code> lacks the granularity for this. It doesn't support callbacks (which would allow you to detect serialization), etc.</p> <p>Options:</p> <ul> <li>implement <code>IXmlSerializable</code> - lots of work (with <code>XmlReader</code>/<code>XmlWriter</code>), and easy to get wrong... don't do it unless you have to</li> <li>use a different serializer (such as <code>DataContractSerializer</code>, which also supports private getters/setters or fields, but doesn't support <em>full</em> xml control) - for example <a href="https://stackoverflow.com/questions/802711#802747">see here</a></li> <li>use a separate DTO; i.e. use your class with private setter in the app, and a <strong>separate</strong> (simpler) class (public get/set) for serialization, perhaps with an implicit conversion operator between them</li> <li>make the get/set public and don't worry about it</li> </ul> <p>I think I'd go for the DTO option; it retains the simple but complete formatting control over the xml, and isn't much work.</p> <pre><code>using System; using System.Xml.Serialization; [XmlType("foo"), XmlRoot("foo")] public class FooDto { [XmlAttribute("bar")] public string Bar { get; set; } public static implicit operator Foo(FooDto value) { return value == null ? null : new Foo(value.Bar); } public static implicit operator FooDto(Foo value) { return value == null ? null : new FooDto { Bar = value.Bar }; } } public class Foo { private readonly string bar; public Foo(string bar) { this.bar = bar; } public string Bar { get { return bar; } } } static class Program { static void Main() { Foo foo = new Foo("abcdefg"); FooDto dto = foo; new XmlSerializer(dto.GetType()).Serialize( Console.Out, dto); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload