c# - deserialize with different root element names -
the following example gives me "[one xmlns=''] not expected." exception
public abstract class baseclass{ } [xmlroot("one")] public class childone : baseclass {} [xmlroot("two")] public class childtwo : baseclass { } class program { private static void main(string[] args) { var ser = new xmlserializer(typeof (baseclass), new type[] {typeof (childone), typeof (childtwo)}); var obj1 = ser.deserialize(new stringreader(@"<?xml version=""1.0""?><one></one>")); var obj2 = ser.deserialize(new stringreader(@"<?xml version=""1.0""?><two></two>")); } }
i need deserialize xml (generated not me). root tag may have different names have map different classes.
ps. know there lot of questions around. have studied them problem still not solved.
no hype building around question. community might thinking stupid question asked idiot. might right. i'll have answer myself beware: answer might stupid too.
i ended probing root element of xml, mapping 1 of known types , deserializing using type. so:
public abstract class baseclass{ } [xmlroot("one")] public class childone : baseclass {} [xmlroot("two")] public class childtwo : baseclass { } class program { private static void main(string[] args) { var known = new type[] {typeof (childone), typeof (childtwo)}; var obj1 = deserialize<baseclass>(@"<?xml version=""1.0""?><one></one>", known); var obj2 = deserialize<baseclass>(@"<?xml version=""1.0""?><two></two>", known); } private static t deserialize<t>(string xml, type[] knowntypes) { type roottype = typeof (t); if (knowntypes.any()) { using (var reader = xmlreader.create(new stringreader(xml))) { reader.movetocontent(); roottype = (from kt in knowntypes let xmlroot = kt.getcustomattributes<xmlrootattribute>().firstordefault() kt.name == reader.name || (xmlroot != null && xmlroot.elementname == reader.name) select kt).firstordefault() ?? typeof(t); } } return (t) new xmlserializer(roottype, knowntypes).deserialize(new stringreader(xml)); } }
Comments
Post a Comment