Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I've created a sample, which will allow you to avoid the unnecessary hidden property when using the XmlSerializer:</p> <pre><code>class Program { static void Main(string[] args) { LocalizationEntry entry = new LocalizationEntry() { CatalogName = "Catalog", Identifier = "Id", Translations = { { "PL", "jabłko" }, { "EN", "apple" }, { "DE", "apfel" } } }; using (MemoryStream stream = new MemoryStream()) { XmlSerializer serializer = new XmlSerializer(typeof(LocalizationEntry)); serializer.Serialize(stream, entry); stream.Seek(0, SeekOrigin.Begin); LocalizationEntry deserializedEntry = (LocalizationEntry)serializer.Deserialize(stream); serializer.Serialize(Console.Out, deserializedEntry); } } } public class LocalizationEntry { public LocalizationEntry() { this.Translations = new TranslationCollection(); } public string CatalogName { get; set; } public string Identifier { get; set; } [XmlArrayItem] public TranslationCollection Translations { get; private set; } } public class TranslationCollection : Collection&lt;Translation&gt; { public TranslationCollection(params Translation[] items) { if (null != items) { foreach (Translation item in items) { this.Add(item); } } } public void Add(string language, string text) { this.Add(new Translation { Language = language, Text = text }); } } public class Translation { [XmlAttribute(AttributeName = "lang")] public string Language { get; set; } [XmlText] public string Text { get; set; } } </code></pre> <p>There are some drawbacks when working with the XmlSerializer class itself. The .NET guidelines encourage you the not provide public-setters for collection-properties (like your translation list). But when you look at the code generated by the XmlSerializer, you'll see that it will use the Setter regardless of it is accessible. This results in a compile-error when the interim class is dynamically loaded by the XmlSerializer. The only way to avoid this, is to make the XmlSerializer think, that it can't actually create an instance of the list and thus won't try to call set for it. If the XmlSerializer detects that it can't create an instance it will throw an exception instead of using the Setter and the interim class is compiled successfully. I've used the param-keyword to trick the serializer into thinking that there is no default-constructor. </p> <p>The only drawback from this solution is that you have to use a non-generic, non-interface type for the property (TranslationCollection) in my example.</p>
 

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