there is a simple hml

<doc> <Dep> <Dprtm_code></Dprtm_code> <Dprtm_name></Dprtm_name> </Dep> </doc> 

the problem is that Dprtm_code can be either <Dprtm_code>234234234</Dprtm_code> or not <Dprtm_code></Dprtm_code> . created a schema:

 //... <xs:element type="xs:long" name="Dprtm_code" nillable="true"/> <xs:element type="xs:string" name="Dprtm_name"/> //... 

I created a class and described these fields in it:

 //... private long? dprtm_codeField; private string dprtm_nameField; [XmlElementAttribute(IsNullable=true)] public long? Dprtm_code { get { return this.dprtm_codeField; } set { this.dprtm_codeField = value; } } public string Dprtm_name { get { return this.dprtm_nameField; } set { this.dprtm_nameField = value; } } //... 

but when deserializing hml with empty code <Dprtm_code></Dprtm_code> , the type conversion error falls. actually the question: how to correctly declare elements that can be empty in xml?

    1 answer 1

    The Xml corresponding to the given scheme and deserialized into the given class should look like this:

     <?xml version="1.0" encoding="UTF-8"?> <doc xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Dep> <Dprtm_code xsi:nil="true"></Dprtm_code> <Dprtm_name></Dprtm_name> </Dep> </doc> 

    That is, there must be an attribute nil from the specified namespace. It is correctly handled by the XmlSerializer (I believe that it is used).

    When serialized, the xsi:nil attribute will be added automatically if necessary.

    Without this attribute, validation according to the scheme also fails.