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

时间:2017-05-03 12:48:48

标签: c# xml xmlserializer xml-deserialization

我正在尝试使用C#中的 XmlSerializer 类来反序列化一些我从某人那里获取的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;

    ...
}

当我运行以下内容时,一切似乎都有效(没有抛出异常),但返回对象中的所有内容都为null,包括Employee对象的内部列表,根据我输入的XML,它不应该为null: / p>

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

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

您可以在this fiddle中看到,如果我接受您的代码并运行它......它可以运行!

然而,我建议有两个类:一个用于&#39; root&#39;每个子元素一个。这样可以减少使用时的混乱:

[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中看到这也有效。