Sunday, 19 October 2014

Error with type cast while deserializing XML using xsd.exe generated schema



I have a simple XML:



<?xml version="1.0" encoding="utf-8"?>
<room>
<item type="computer">
<x-coord>1</x-coord>
<y-coord>2</y-coord>
</item>
<item type="chair">
<x-coord>4</x-coord>
<y-coord>5</y-coord>
</item>
</room>


And I've generated XML Schema for it, as follows:



<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="room" xmlns="" xmlns:xs="http://ift.tt/tphNwY" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="room" msdata:IsDataSet="true" msdata:Locale="en-US">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="item">
<xs:complexType>
<xs:sequence>
<xs:element name="x-coord" type="xs:string" minOccurs="0" msdata:Ordinal="0" />
<xs:element name="y-coord" type="xs:string" minOccurs="0" msdata:Ordinal="1" />
</xs:sequence>
<xs:attribute name="type" type="xs:string" />
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>


Because I want my x-coord and y-coord fields to hold an Integer value, I've changed xs:string to xs:int, like this:



<xs:element name="x-coord" type="xs:int" minOccurs="0" msdata:Ordinal="0" />
<xs:element name="y-coord" type="xs:int" minOccurs="0" msdata:Ordinal="1" />


I've read somewhere that this should hold Int32 value, so I've changed my generated Room.cs to have:



[System.Xml.Serialization.XmlElementAttribute("y-coord", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public System.Int32 ycoord
{
get {
return this.ycoordField;
}
set {
this.ycoordField = value;
}
}


for both x and y coordinate. However, I still have an error with Strong Types and Cast Exception:



+ _x_coord '(new System.Linq.SystemCore_EnumerableDebugView<NA2.room.itemRow>(this.Items.tableitem)).Items[0]._x_coord' threw an exception of type 'System.Data.StrongTypingException' int {System.Data.StrongTypingException}

+ base {System.Data.StrongTypingException: The value for column 'x-coord' in table 'item' is DBNull. ---> System.InvalidCastException: Specified cast is not valid.


It only works with xs:string and public String ycoord. Only then the values are stored without any error but it is not what I want.


Do you know where is the problem here?


No comments:

Post a Comment