Generise : Deserialize Xml to a specific class of

2019-08-29 08:43发布

问题:

Input pre-processed xml files to map a specific transaction type

Say I have transactionTypeA transactionTypeB transactionTypeC, (all inherited from TransactionTypes). the following code, just for reference, is good for a specific transaction type. for example, mapping xml data into transactionTypeA:

byte[] byteArray = Encoding.UTF8.GetBytes(xmlContent);
MemoryStream tempMemoryStream = new MemoryStream(byteArray);
DataContractSerializer serializer = new DataContractSerializer(typeof(transactionTypeA));
transactionTypeA variavlename= (transactionTypeA)serializer.ReadObject(tempMemoryStream);

Now, I want to make it generic, so that when an xml file is in, I can tell which specific transaction it is.

DataContractSerializer serializer = new DataContractSerializer(typeof(ThatCorrespondingTransactionType));
    ThatCorrespondingTransactionType variavlename= (ThatCorrespondingTransactionType)serializer.ReadObject(tempMemoryStream)

Any help please? I have tried to just use the root parent TransactionTypes, but it gives : SerializationException was unhandled by user code.

Thanks a lot.