C# 如何使用相同名称的嵌套元素反序列化XML文件,其中一个元素是root?
我试图使用C中的XmlSerializer类来反序列化我从某人那里提取的一些XML。不幸的是,它们的根元素名为Employee,而根元素中的内部元素也名为Employee:C# 如何使用相同名称的嵌套元素反序列化XML文件,其中一个元素是root?,c#,xml,xmlserializer,xml-deserialization,C#,Xml,Xmlserializer,Xml Deserialization,我试图使用C中的XmlSerializer类来反序列化我从某人那里提取的一些XML。不幸的是,它们的根元素名为Employee,而根元素中的内部元素也名为Employee: <Employee xmlns="http://www.testxmlns.com/employee"> <Employee> <OtherElement>OE</OtherElement> ... </Employee>
<Employee xmlns="http://www.testxmlns.com/employee">
<Employee>
<OtherElement>OE</OtherElement>
...
</Employee>
<Employee>
<OtherElement>OE</OtherElement>
...
</Employee>
</Employee>
当我运行以下命令时,一切似乎都正常,没有抛出异常,但返回对象中的所有内容都为null,包括Employee对象的内部列表,根据我输入的XML,该列表不应为null:
Employee retObj;
XmlSerializer serializer = new XmlSerializer(typeof(Employee));
using (TextReader sr = new StringReader(xmlString))
{
retObj = (Employee)serializer.Deserialize(sr);
}
return retObj;
任何帮助都将不胜感激 你可以从中看出,如果我把你的代码运行起来。。。它起作用了
但是,我建议有两个类:一个用于“根”,另一个用于每个子元素。这将减少以下情况的混淆:
[XmlRoot("Employee", Namespace = "http://www.testxmlns.com/employee")]
public class EmployeeRoot
{
[XmlElement("Employee")]
public Employee[] Employees { get; set; }
}
public class Employee
{
public string OtherElement { get; set; }
}
你可以看到,这也是可行的
[XmlRoot("Employee", Namespace = "http://www.testxmlns.com/employee")]
public class EmployeeRoot
{
[XmlElement("Employee")]
public Employee[] Employees { get; set; }
}
public class Employee
{
public string OtherElement { get; set; }
}