I’m working on a RESTful web-service with the WCF Web API. Another party provided the XSD files. I generated the C# classes with xsd.exe. However the schema contains one complex type that I’m having an issue with:
<xs:complexType name="SearchableField">
<xs:choice>
<xs:element name="NumericValue" type="xs:float" minOccurs="1" maxOccurs="1"/>
<xs:element name="BooleanValue" type="xs:boolean" minOccurs="1" maxOccurs="1"/>
</xs:choice>
<xs:attribute name="type" type="SearchableFieldType" use="required"/>
</xs:complexType>
This is the generated code for the complex type:
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class SearchableField {
private object itemField;
private string typeField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("BooleanValue", typeof(bool), Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.Xml.Serialization.XmlElementAttribute("NumericValue", typeof(float), Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public object Item {
get {
return this.itemField;
}
set {
this.itemField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string type {
get {
return this.typeField;
}
set {
this.typeField = value;
}
}
}
Question: How to initialize type Item property – which is a plain object – so that it can be serialized according to the schema.
Constraint: The schema is already specified so I may not change the XSD file.
Here’s an example of the XML element how it is expected to look like:
<SearchableFields>
<SearchableField type="MEGAPIXELS">
<NumericValue>12</NumericValue>
</SearchableField>
<SearchableField type="WEATHER_RESISTANT">
<BooleanValue>true</BooleanValue>
</SearchableField>
<SearchableField type="WATER_RESISTANT">
<BooleanValue>false</BooleanValue>
</SearchableField>
</SearchableFields>
(comments)
Indeed –
NumericValueis declared asfloatin the xml / C#, and using anintis going to introduce an invalid cast; this works, however:with output: