Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I just discovered this. <code>XmlSerialier</code> looks for a <code>XXXSpecified</code> boolean property to determine if it should be included. This should solve the problem nicely.</p> <pre><code>[Serializable] public class MyClass { public int Age { get; set; } [XmlIgnore] public bool AgeSpecified { get { return Age &gt;= 0; } } public int MyClassB { get; set; } } [Serializable] public class MyClassB { public int RandomNumber { get; set; } } </code></pre> <p>Proof:</p> <pre><code>static string Serialize&lt;T&gt;(T obj) { var serializer = new XmlSerializer(typeof(T)); var builder = new StringBuilder(); using (var writer = new StringWriter(builder)) { serializer.Serialize(writer, obj); return builder.ToString(); } } static void Main(string[] args) { var withoutAge = new MyClass() { Age = -1 }; var withAge = new MyClass() { Age = 20 }; Serialize(withoutAge); // = &lt;MyClass&gt;&lt;MyClassB&gt;0&lt;/MyClassB&gt;&lt;/MyClass&gt; Serialize(withAge); // = &lt;MyClass&gt;&lt;Age&gt;20&lt;/Age&gt;&lt;MyClassB&gt;0&lt;/MyClassB&gt;&lt;/MyClass&gt; } </code></pre> <hr /> <p><strong>Edit</strong>: Yes, it is a documented feature. See the <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx" rel="noreferrer">MSDN entry for <code>XmlSerializer</code></a></p> <blockquote> <p>Another option is to use a special pattern to create a Boolean field recognized by the XmlSerializer, and to apply the XmlIgnoreAttribute to the field. The pattern is created in the form of propertyNameSpecified. For example, if there is a field named "MyFirstName" you would also create a field named "MyFirstNameSpecified" that instructs the XmlSerializer whether to generate the XML element named "MyFirstName".</p> </blockquote>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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