我想将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”的集合?请指导!
答案 0 :(得分:1)
试试这样:
[TestFixture]
public class SerializeTest
{
[Test]
public void SerializeEmpTest()
{
EmpCollection empCollection = new EmpCollection()
{
new EmpInfo() {Code = "1", FirstName = "Anita"},
new EmpInfo() {Code = "1", FirstName = "Johan"}
};
string xmlString = empCollection.GetXmlString();
}
}
[XmlType, XmlRoot]
public class EmpCollection : List<EmpInfo>
{
}
[XmlType]
public class EmpInfo
{
public string Code;
public string FirstName;
}
public static class Extenstion
{
public static string GetXmlString<T>(this T objectToSerialize)
{
XmlSerializer xmlSerializer = new XmlSerializer(objectToSerialize.GetType());
StringBuilder stringBuilder = new StringBuilder();
string xml;
using (var xmlTextWriter = new XmlTextWriter(new StringWriter(stringBuilder)))
{
xmlSerializer.Serialize(xmlTextWriter, objectToSerialize);
xml = stringBuilder.ToString();
}
return xml;
}
}