如何使用同名嵌套元素反序列化 XML 文件,其中一个元素是根?

How to deserialize XML file with nested elements of same name, with one of elements are root?

我正在尝试使用 C# 中的 XmlSerializer class 来反序列化我从某人那里提取的一些 XML。不幸的是,它们的根元素名为 "Employee",然后该根元素内的内部元素也被命名为 "Employee":

<Employee xmlns="http://www.testxmlns.com/employee">
    <Employee>
       <OtherElement>OE</OtherElement>
       ...
    </Employee>
    <Employee>
       <OtherElement>OE</OtherElement>
       ...
    </Employee>
</Employee>

我能够 find another question that is very similar,但不完全是。这是我当前对象的样子:

[XmlType("Employee")]
[XmlRootAttribute(Namespace = "http://www.testxmlns.com/employee", IsNullable = true)]
public class Employee
{
    [XmlElement("Employee")]
    public Employee[] InnerEmployee;

    [XmlElement("OtherElement")]
    public String OtherElement;

    ...
}

当我运行以下时,似乎一切正常(没有抛出异常),但返回对象中的所有内容都是空的,包括Employee对象的内部列表,根据XML 我正在输入:

Employee retObj;
XmlSerializer serializer = new XmlSerializer(typeof(Employee));
using (TextReader sr = new StringReader(xmlString))
{
    retObj = (Employee)serializer.Deserialize(sr);
}
return retObj;

如有任何帮助,我们将不胜感激!

您可以在 this fiddle 中看到,如果我使用您的代码 运行 它...它可以工作!

不过,我建议使用两个 类:一个用于 'root',一个用于每个子元素。这将减少使用时的混乱:

[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; }
}

您可以在 this fiddle 中看到这也有效。