I have this class that has a property that is a array of another class type
[XmlRoot(ElementName = "student")]
public class Student
{
[XmlElement(ElementName = "name")]
public string Name { get; set; }
[XmlElement(ElementName = "email")]
public string Email { get; set; }
[XmlIgnoreAttribute]
public string Department { get; set; }
[XmlElement(ElementName = "topics")]
public Topic[] Topics { get; set; }
}
[XmlType(TypeName = "topic")]
public class Topic
{
[XmlElement(ElementName = "topiccode")]
public string TopicName;
}
When I try to serialize this into an XML it is messing the top tag that is the parent of Topic code. So while I expect to get this
<student>
<name>Max Power</name>
<email>test999@email.com</email>
<topics>
<topic>
<topiccode>CAGLENN_17</topiccode>
</topic>
</topics>
</student>
What I get instead is the topic
tag is omitted
<student>
<name>Max Power</name>
<email>test999@email.com</email>
<topics>
<topiccode>CAGLENN_17</topiccode>
</topics>
</student>
Is there a different option I am suppose to use, or maybe I am not setting something correctly?
You need to change to use [XmlArray(ElementName = "topics")]
:
[XmlArray(ElementName = "topics")]
public Topic[] Topics { get; set; }
The reason is that by using [XmlElement(ElementName = "topics")]
you are telling the serializer that you don't want a containing element, and that each entry should exist in the main object.
We can see this in action if we add a second topic:
<?xml version="1.0" encoding="utf-16"?>
<student xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<name>Max power</name>
<email>test999@email.com</email>
<topics>
<topiccode>CAGLENN_17</topiccode>
</topics>
<topics>
<topiccode>CAGLENN_18</topiccode>
</topics>
</student>
[XmlArray(ElementName = "topics")]
, on the other hand, specifies the name for the element that contains the array's items.