We are facing a situation where the DataContract serializer (a WCF service) is not deserializing repeating XML elements without container element into a list; the list property ends up with zero elements.
The datacontracts we have:
[DataContract]
public class Requestor
{
[DataMember(IsRequired = true, Order = 0)]
public string RequestorRole;
[DataMember(IsRequired = true, Order = 1)]
public string RequestorGivenName;
[DataMember(IsRequired = true, Order = 2)]
public string RequestorSurName;
[DataMember(IsRequired = false, Order = 3)]
public List<RequestorIdentification> RequestorIdentification { get; set; }
}
[DataContract]
public class RequestorIdentification
{
[DataMember(IsRequired = true, Order = 0)]
public string IdentificationID;
[DataMember(IsRequired = true, Order = 1)]
public string IdentificationCategoryCode;
}
The XML we want to deserialize:
<Requestor xmlns="http://schemas.datacontract.org/2004/07/Serialization">
<RequestorRole>Physicians</RequestorRole>
<RequestorGivenName>Rich</RequestorGivenName>
<RequestorSurName>Smith</RequestorSurName>
<RequestorIdentification>
<IdentificationID>AB1234567</IdentificationID>
<IdentificationCategoryCode>DEA</IdentificationCategoryCode>
</RequestorIdentification>
<RequestorIdentification>
<IdentificationID>0123456789</IdentificationID>
<IdentificationCategoryCode>NPI</IdentificationCategoryCode>
</RequestorIdentification>
</Requestor>
How can we resolve the issue using the DataContract serializer?
So far we have found no way to make it work, and this page https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/collection-types-in-data-contracts was not of much help.
The same issue was resolved for the XmlSerializer in this question:
Deserializing into a List without a container element in XML
To deserialize the XML shown in the OP, one can use XmlElement. However, this requires the use of XmlSerializer instead of DataContractSerializer for serialization and deserialization.
According to this post
The code below shows how one can deserialize the XML shown in the OP.
Create a Windows Forms App (.NET Framework)
Add Reference (System.Runtime.Serialization)
VS 2019
The following using directives are used in the code below:
using System;using System.Collections.Generic;using System.IO;using System.Runtime.Serialization;using System.Text;using System.Xml;using System.Xml.Serialization;Create a class (name: RequestorRequestorIdentification.cs)
Create a class (name: Requestor.cs)
Note: The use of XmlElement requires the use of XmlSerializer instead of DataContractSerializer for serialization and deserialization.
Create a class (name: HelperXml.cs)
Usage (deserialize):
Usage (serialize):
Additional Resources: