How to deserialize an XML file into a class without using attributes

81 views Asked by At

I've been attempting to perform XML deserialization involving a nested object into a C# class without using attributes. The XML element is "Man," while the corresponding C# class is named "ManDTO." A man has Hobbies which is a list of HobbyDTO as shown below.

<?xml version="1.0" encoding="utf-8" ?> 
<Man>
  <Hobbies>
    <Hobby>
        
    </Hobby> 
</Hobbies>      
</Man>

The class is

public class ManDTO
{
    public List<HobbyDTO> Hobbies{ get; set; }
}

This works for other properties but not for the nested ones.

XmlRootAttribute root= new XmlRootAttribute();
root.ElementName = rootElementName;

XmlAttributes attribs = new XmlAttributes();
attribs.XmlElements.Add(new XmlElementAttribute("HobbyDTO")); 

XmlAttributeOverrides overrides = new XmlAttributeOverrides();
overrides.Add(typeof(List<HobbyDTO>), "Hobbies", attribs);

var result = new XmlSerializer(typeof(ManDTO), overrides, new Type[] { typeof(HobbyDTO) }, root, "", "" ).Deserialize(xml);
0

There are 0 answers