我试图将具有对象列表的XML解析为C#对象。我已经简化了XML,它的结构如下所示:
[Serializable, XmlRoot("Form")]
public class MyXML
{
public string Name { get; set; }
[XmlElement("Employee")]
public List<Employee> employeeList;
}
public class Employee
{
public string EmployeeNumber { get; set; }
[XmlElement("Addresses")]
public List<Addresses> AddressesList { get; set; }
}
public class Addresses
{
public string Line1 { get; set; }
public string Line2 { get; set; }
}
XML看起来像这样:
<Form >
<Name>John</Name>
<Employee>
<EmployeeNumber>6</EmployeeNumber>
<Addresses>
<Line1>1123</Line1>
<Line2>456</Line2>
</Addresses>
<Addresses>
<Line1>567</Line1>
<Line2>8798</Line2>
</Addresses>
</Employee>
</Form>
我可以成功序列化表单/员工级别,但地址列表不会被解除序列并且为空。任何想法为什么它不起作用?
答案 0 :(得分:2)
You didn't post how you are trying to deserialize but the following code worked for me to deserialize everything successfully without changing anything in your classes:
string xml = File.ReadAllText("XMLFile1.xml");
XmlSerializer serializer = new XmlSerializer(typeof(MyXML));
using (StringReader reader = new StringReader(xml))
{
var myXml = (MyXML)serializer.Deserialize(reader);
}