I’m attempting to serialize a Level object that looks something like this:
public class Level
{
//Some XmlAtributes
[XmlElement]
public List<Question> questions;
}
public class Question
{
//Some XmlAttributes
[XmlArray("Answers")]
public List<string> answers;
}
into and XML file that looks like this:
<Level time="2">
<Question type="multiplechoice">
<Answers correct="b">
<a>Answer 1</a>
<b>Answer 2</b>
<c>Answer 3</c>
<d>Answer 4</d>
</Answers>
</Question>
<Question>
...
</Question>
</Level>
I can already serialize this except for the element names under <Answers>. Notice how each element gets an incremented name, rather than all being the same (e.g. <string> by default). Is this possible? I know I can rename the elements with [XmlArrayItem("ItemName")], but this applies the same name to all elements in the array.
If anyone else happens across this, here is the solution I went with (thanks to IAbstract’s tip):
I made Answer it’s own class as it has attributes and I don’t need to override the serialization behavior for anything else within the Question class. The extra reader.Read() is to make sure the reader is moved to the next tag after , or else deserialization won’t continue after dealing with Answer.
It’s not 100% perfect, but for my implementation it’s enough.