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?
I ended up using XSLT to ensure the node(s) I was after weren’t the root.
Basically I’ve a XSLT file containing:
(Not sure if this XSLT is ideal, would love some comments).
This wraps a around my inbound XML from the api. My previously mentioned
Personclass has a[XmlType("person")]attribute applied to it, armed with that I can do: