Deserialize XML generated from .NET Core 3.1 Web API
.NET Core 2.x used to generate "normal" XML in a format that was easily deserializeable using standard methods, but now, in v3.1.5 at least, using AddXmlDataContractSerializerFormatters in your startup configuration to enable an API to return XML returns responses that look like this…
<ArrayOfArrayOfKeyValueOfstringanyType xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays"> <ArrayOfKeyValueOfstringanyType> <KeyValueOfstringanyType> <Key>districtId</Key> <Value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:decimal">122</Value> </KeyValueOfstringanyType> <KeyValueOfstringanyType> <Key>amount</Key> <Value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:decimal">1888810.42</Value> </KeyValueOfstringanyType> </ArrayOfKeyValueOfstringanyType> <ArrayOfKeyValueOfstringanyType> <KeyValueOfstringanyType> <Key>districtId</Key> <Value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:decimal">205</Value> </KeyValueOfstringanyType> <KeyValueOfstringanyType> <Key>amount</Key> <Value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:decimal">1207736.00</Value> </KeyValueOfstringanyType> </ArrayOfKeyValueOfstringanyType> </ArrayOfArrayOfKeyValueOfstringanyType>
When trying to deserialize this in client code using
var serializer = new XmlSerializer(typeof(List<MyDto>)); var reader = new StringReader(content); var list = (List<MyDto>)serializer.Deserialize(reader);
it understandably throws the exception
InvalidOperationException: <ArrayOfArrayOfKeyValueOfstringanyType xmlns='http://schemas.microsoft.com/2003/10/Serialization/Arrays'> was not expected.
The DTO used in this case is simply
public class MyDto { public decimal DistrictId { get; set; } public decimal Amount { get; set; } }
so it is expecting XML similar to this, which would work fine
<ArrayOfMyDto> <MyDto> <DistrictId>122</DistrictId> <Amount>1888810.42</Amount> </MyDto> ... more items in list here </ArrayOfMyDto>
Anyone know how to deserialize this XML format now returned in .NET Core 3.1.5?
private void deserializxml() { string myxmlstr = @"<ArrayOfMyDto> <MyDto> <DistrictId>122</DistrictId> <Amount>1888810.42</Amount> </MyDto> </ArrayOfMyDto>"; XmlSerializer serializer = new XmlSerializer(typeof(List<MyDto>), new XmlRootAttribute("ArrayOfMyDto")); StringReader stringReader = new StringReader(myxmlstr); List<MyDto> addList = (List<MyDto>)serializer.Deserialize(stringReader); }