I'm attempting to use DataContractSerializer to read an xml file and instantiate objects from the xml but I'm not able to get an embedded class to deserialize properly. I've written and tested numerous combinations of DatContract attributes, xml and deserializing code with no success. I've read so many articles but there are few that go into detail about deserializing with an embedded class.
I've used XMLSerializer in the past and had no problems.
Below is a simple example which illustrates the problem. The Child and GrandChild objects in the Parent class are instantiated but the properties in the classes are not populated with the values in the XML file.
Thanks in advance for any help. I'm sure I will forget the answer once this is resolved :)
//XML
="1.0"="utf-8"
<Parent>
<Child>
<Age>15</Age>
<EyeColor>blue</EyeColor>
</Child>
<FirstName>Joe</FirstName>
<Grandchild>
<Age>15</Age>
<EyeColor>blue</EyeColor>
</Grandchild>
<LastName>Smith</LastName>
</Parent>
[DataContract(Namespace = "")]
public class Parent
{
private Child _Child;
private Grandchild _Grandchild;
private string _FirstName;
private string _LastName;
[DataMember]
public Child Child
{
get
{
return _Child;
}
set
{
_Child = value;
}
}
[DataMember]
public Grandchild Grandchild
{
get
{
return _Grandchild;
}
set
{
_Grandchild = value;
}
}
[DataMember]
public string FirstName
{
get
{
return _FirstName;
}
set
{
_FirstName = value;
}
}
[DataMember]
public string LastName
{
get
{
return _LastName;
}
set
{
_LastName = value;
}
}
}
[DataContract]
public class Child
{
private int _Age;
private string _EyeColor;
[DataMember]
public int Age
{
get
{
return _Age;
}
set
{
_Age = value;
}
}
[DataMember]
public string EyeColor
{
get
{
return _EyeColor;
}
set
{
_EyeColor = value;
}
}
}
[DataContract]
public class Grandchild
{
private int _Age;
private string _EyeColor;
[DataMember]
public int Age
{
get
{
return _Age;
}
set
{
_Age = value;
}
}
[DataMember]
public string EyeColor
{
get
{
return _EyeColor;
}
set
{
_EyeColor = value;
}
}
}
DataContractSerializer ser = new DataContractSerializer(typeof(Parent));<br />
FileStream fs = new FileStream("D:/Sandbox/WebApplication1/xml/parent6.xml", FileMode.Open);<br />
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());<br />
<br />
Parent parent = (Parent)ser.ReadObject(reader, true);<br />
<br />
reader.Close();
// Resulting Object
parent(instantiated)
parent.Child (instantiated)
parent.Child.Age = 0
parent.Child.EyeColor = null
parent.FirstName = "Joe"
parent.GrandChild (instantiated)
parent.GrandChild.Age = 0
parent.GrandChild.EyeColor = null
parent.LastName="Smith"