I am trying to deserialize an XML file with a List<object> into a DataContract class. With the below code I am able to deserialize every property, except the List<object>.
Code:
[DataContract(Namespace = "http://myNamespace")]
[KnownType(typeof(List<Child>))]
public class Person
{
[DataMember]
public List<Child> Children { set; get; }
[DataMember]
public DateTime birthdate { set; get; }
[DataMember]
public string SSN { set; get; }
[DataMember]
public string Gender { set; get; }
[DataMember]
public string Name { set; get; }
[DataMember]
public int PersonID { set; get; }
public Person()
{
Children=new List<Child>();
}
}
[DataContract]
public class Child
{
[DataMember]
public string Name { set; get; }
}
class Program
{
static void Main(string[] args)
{
var rm = new ResourceManager("WCFExample.Resource1", Assembly.GetExecutingAssembly());
string xml = rm.GetString("Person.xml");
Person r = null;
var ms = new MemoryStream(Encoding.Default.GetBytes(xml));
using (var reader = XmlDictionaryReader.CreateTextReader(ms, new XmlDictionaryReaderQuotas()))
{
DataContractSerializer ser = new DataContractSerializer(typeof(Person));
r = (Person)ser.ReadObject(reader, true);
reader.Close();
}
Console.WriteLine( "Child name:"+r.Children[0].Name);
Console.WriteLine( "PersonID:"+r.PersonID );
Console.WriteLine( "Navn:"+r.Name);
}
}
XML file (Person.xml):
<Person xmlns="http://myNamespace">
<Children>
<Child>
<Name>chinnu</Name>
</Child>
<Child>
<Name>bittu</Name>
</Child>
</Children>
<birthdate>1980-12-31</birthdate>
<SSN>10067136132</SSN>
<Gender>M</Gender>
<Name>Ravi</Name>
<PersonID>1</PersonID>
</Person>
Output: Though I have 2 child objects as shown in above XML, still the Children collection is always empty. So Children[0].Name is throwing exception. Not sure what I am missing here. Please help!
SOLUTION: 1
Replace:
[DataContract]
public class Child
{
[DataMember]
public string Name { set; get; }
}
With
[DataContract(Namespace = "http://myNamespace")]
public class Child
{
[DataMember]
public string Name { set; get; }
}
Using the same namespace on Child element also. However, it works only if namespaces are the same. I would love to know how to handle if both Person and Child are in different namespaces J
No comments:
Post a Comment