Question:
have a simple hml
<doc>
<Dep>
<Dprtm_code></Dprtm_code>
<Dprtm_name></Dprtm_name>
</Dep>
</doc>
the problem is that Dprtm_code can be either filled with <Dprtm_code>234234234</Dprtm_code>
and 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"/>
//...
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 an empty code <Dprtm_code></Dprtm_code>
, a type conversion error occurs. actually the question: how to correctly declare elements that can be empty in xml?
Answer:
The Xml corresponding to the given schema and deserializing 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 a nil
attribute from the specified namespace. It is handled correctly by the XmlSerializer
(I believe it is used).
On serialization, the xsi:nil
attribute will be added automatically as needed.
Schema validation also fails without this attribute.