Xml Serialization

To automatically create support classes to help with Xml serialization, you can use a great tool Xsd2Code.

While using the tool I came across a feature which I vaguely remember reading a while ago, ‘hiding xml elements’.

Eg 

public class Contact
{
    public string Name { get; set; }
}

The class above will generate the following xml scheme. Note the 'minOccurs' attrubute.

<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Contact" nillable="true" type="Contact" />
  <xs:complexType name="Contact">
    <xs:sequence>
      <xs:element minOccurs="1" maxOccurs="1" name="Name" type="xs:string" />
    </xs:sequence>
  </xs:complexType>
</xs:schema>

However to generate the correct scheme that I needed, I wanted the Name element to be Nullable

<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Contact" nillable="true" type="Contact" />
  <xs:complexType name="Contact">
    <xs:sequence>
      <xs:element minOccurs="0" maxOccurs="1" name="Name" type="xs:string" />
    </xs:sequence>
  </xs:complexType>
</xs:schema>

The way to achieve this with Xmlserialization is to use the ‘propertySpecified’ convention.

public class Contact
{
    public string? Name { get; set; }

    [XmlIgnore]
    public bool NameSpecified { get { return Name.HasValue; } }
}

The public property is made Nullable.

Add the ‘Specified’ property. The property name must match the public property plus the string ‘Specified’, this will instruct the Xmlserializer not to serialise the member.