I want to serialize an xml string into collection of objects, but I can get get only first object. If I add more objects in xml, then it errors out. Not sure what I am missing. I tried declaring type as Emp[]
Here are my both “Emp” xml strings
string empsworking = "<?xml version='1.0' encoding='utf-8'?><Emp><EmpInfo><Code>vv</Code><FirstName>van</FirstName><LastName>sa</LastName><Destination>sc</Destination></EmpInfo><EmpInfo><Code>rr</Code><FirstName>ro</FirstName><LastName>sa</LastName><Destination>ph</Destination></EmpInfo></Emp>";
string empsNotworking = "<?xml version='1.0' encoding='utf-8'?><Emp><EmpInfo><Code>vv</Code><FirstName>van</FirstName><LastName>sa</LastName><Destination>sc</Destination></EmpInfo></Emp>";
My classes look like
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public class Emp
{
/// <remarks/>
public EmpInfo EmpInfo { get; set; }
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
}
/// <remarks/>
[XmlRoot(ElementName = "EmpInfo")]
public class EmpInfo
{
/// <remarks/>
public string Code;
/// <remarks/>
public string FirstName;
/// <remarks/>
public string LastName;
/// <remarks/>
public string Destination;
}
and my code to serialize is
StringReader stream = null;
XmlTextReader reader = null;
Emp empprofile;
try
{
// serialise to object
XmlSerializer serializer = new XmlSerializer(typeof(Emp));
stream = new StringReader(emps); // read xml data
reader = new XmlTextReader(stream); // create reader
// covert reader to object
empprofile = (Emp)serializer.Deserialize(reader);
}
catch
{
return null;
}
finally
{
if (stream != null) stream.Close();
if (reader != null) reader.Close();
}
I can only read/get object with empworking.
How can get it as collection of “EmpInfo”? Please guide!
Try like this: