c# - Deserialize xml into a Linq to SQL object -


i need read in xml data posted external systems, formatted follows:

<applicant>   <firstname>john</firstname>   <lastname>smith</lastname>   <address>12 main st</address> </applicant> 

this direct mapping of linq sql applicant class, excluding few properties.

what's best way deserialize xml linq sql object, can insert directly database? i'd validate incoming xml , handle specific errors if possible.

thanks in advance!

if direct map, should able use directly, long types public , have public parameterless constructors, , properties (including lists) get/set.

if need tweak names there xmlserializer constructor allows specify attributes. ideal scenario, must cache , re-use serializer if use constructor overload, otherwise leak memory (the dynamic assemblies not collected).

here's full example removes 1 property (xmlignore), changes attribute, , leaves third element.

using system; using system.io; using system.xml.serialization; public class foo {     public int { get; set; }     public string b { get; set; }     public int c { get; set; } } static class program {     static readonly xmlserializer serializer;     static program()     {         xmlattributeoverrides or = new xmlattributeoverrides();         or.add(typeof(foo), "a", new xmlattributes { // change attrib             xmlattribute = new xmlattributeattribute("tweaked")         });         or.add(typeof(foo), "b", new xmlattributes {             xmlignore = true // turn 1 off         });         // leave c default named element         serializer = new xmlserializer(typeof(foo), or);     }     static void main()     {         foo foo = new foo { = 123, b = "def", c = 456 }, clone;         string xml;         using (stringwriter sw = new stringwriter())         {             serializer.serialize(sw, foo);             xml = sw.tostring();         }         using (stringreader sr = new stringreader(xml)) {             clone = (foo)serializer.deserialize(sr);         }         console.writeline(xml);         console.writeline();         console.writeline(clone.a);         console.writeline(clone.b);         console.writeline(clone.c);     } } 

note if need change things @ type level (such [xmlinclude]) can via partial class linq-to-sql generates; example:

namespace my.dal.namespace {     // add type attribute someentity     [xmlinclude(typeof(somederivedentity))]     partial class someentity { }  } 

Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -