I'm trying to write a generic method that can be used to deserialize xml to an array of objects.
Given XML that looks like so:
<people>
<person>
<someElement>content</someElement>
</person>
<person>
<someElement>more content</someElement>
</person>
</people>
Shown in the below code as xmlDoc
. And a person
class as T
XmlNodeReader reader = new XmlNodeReader(xmlDoc.DocumentElement);
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T[]), new XmlRootAttribute(xmlDoc.DocumentElement.Name));
results = xmlSerializer.Deserialize(reader) as T[];
This works as expected, and returns person[]
with 2 entries.
However, in the API I am working with, if there is only 1 result returned, it just returns:
<person>
<someElement>content</someElement>
</person>
And my deserialization breaks down. person[]
remains empty.
Any thoughts on the best way to implement this?
Edit
I'm contemplating running an XSLT in between, and passing the name of T
in, if it matches the root node, then add a wrapping node?