thomasdclark
thomasdclark

Reputation: 474

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

I am trying to use the XmlSerializer class in C# to deserialize some XML that I am pulling from someone. Unfortunately, they have their root element named "Employee", and then the inner elements inside that root element are also named "Employee":

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

I was able to find another question that is very similar, but not exactly. Here is what my current object looks like:

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

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

    ...
}

When I run the following, everything seems to work (no exceptions thrown), but everything in the returned object is null, including the inner list of Employee objects, which should not be null based on the XML I am inputting:

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

Any help would be appreciated!

Upvotes: 1

Views: 1816

Answers (1)

Charles Mager
Charles Mager

Reputation: 26213

You can see in this fiddle that if I take your code and run it... it works!

What I would suggest, however, is to have two classes: one for the 'root' and one for each child element. This would make it less confusing to work with:

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

You can see in this fiddle that this also works.

Upvotes: 2

Related Questions