I need to read in XML data posted from external systems, which will be formatted roughly as follows:
<Applicant>
<FirstName>John</FirstName>
<LastName>Smith</LastName>
<Address>12 Main St</Address>
</Applicant>
This is a direct mapping of my Linq to SQL Applicant class, excluding a few properties.
What’s the best way to deserialize xml into a Linq to SQL object, so I can then insert directly into my database? I’d also like to validate the incoming XML and handle specific errors if possible.
Thanks in advance!
If it is a direct map, you should just be able to use it directly, as long as the types as public and have public parameterless constructors, and the properties (including lists) are get/set.
If you need to tweak the names there is an
XmlSerializerconstructor that allows you to specify all the attributes. This is ideal for your scenario, but you must cache and re-use the serializer if you use this constructor overload, otherwise you will leak memory (the dynamic assemblies are not collected).Here’s a full example that removes one property (
XmlIgnore), changes another to an attribute, and leaves a third as an element.Note also that if you only need to change things at the type level (such as
[XmlInclude]) then you can do this via thepartial classthat LINQ-to-SQL generates; for example: