0

I'm writing a web service to deserialize XML files, map them to POCOs and save them to a database. I have a XSD defining the model, and use xsd2code to generate the models.

Here's an example. In my XSD definition, I have the following property:

<xs:element name="SeniorityDate" type="xs:date" nillable="true" 
minOccurs="0">
    <xs:annotation>
        <xs:documentation>A nullable date.</xs:documentation>
    </xs:annotation>
</xs:element>

xsd2code generates the following (note that the property's data type is Nullable DateTime):

/// <summary>
/// A nullable date.
/// </summary>
[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, DataType = "date", IsNullable = true)]
public System.Nullable<System.DateTime> SeniorityDate
{
    get {return this._seniorityDate;}
    set {this._seniorityDate = value;}
}

I make a PUT call, trying different ways of entering a null value for the property, none of which work:

<SeniorityDate></SeniorityDate>
<SeniorityDate/>
<SeniorityDate xsi:nil="true" />

All of these return a HttpRequestException, despite the property being marked as nullable.

If I manually add the annotation [XmlElement(IsNullable=true)] (i.e. XmlElement instead of the automatically generated XmlElementAttribute), then a null value will be accepted.


Is there a way for the XML deserialization to allow for nulls values where properties are annotated with [XmlElementAttribute(IsNullable=true)]? Or can I somehow make xsd2code put [XmlElement(IsNullable=true)] over properties?

AdSNobrega
  • 23
  • 1
  • 6
  • DateTime values cannot be null. So change the set : set {this._seniorityDate = value == null ? new DataTime() : value;} – jdweng Dec 07 '17 at 22:40
  • @jdweng In this case, we're talking about a nullable DateTime. xsd2code gives it the right data type, but not the annotations for deserialization/validation. Thanks for replying, though. – AdSNobrega Dec 08 '17 at 08:47
  • Never heard of a Nullable DateTime. – jdweng Dec 08 '17 at 09:34

0 Answers0