我想将 xml 字符串序列化为对象集合,但我只能获取第一个对象。如果我在 xml 中添加更多对象,则会出错。不知道我错过了什么。我尝试将类型声明为 Emp[]
这是我的两个“Emp”xml 字符串
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>";
我的课看起来像
[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;
}
我的序列化代码是
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();
}
我只能通过 empworking 读取/获取对象。如何将其作为“EmpInfo”的集合?请指导!