asp.net - How to convert XML into Object format in C# -


i wanted convert xml in object format

- <information> - <item>   <key>name</key>    <value>namevalue</value>    </item> - <item>   <key>age</key>    <value>17</value>    </item> - <item>   <key>gender</key>    <value>male</value>    </item> - </information> 

object like,

person.name = "name value" person.age = 17 person.gender = "male" 

you can xdocument reflection achieving following way:

xdocument xdocument = xdocument.parse(myxml);  var nodes = xdocument.descendants("item");  // type contained in name string type type = typeof(person);  // create instance of type object instance = activator.createinstance(type);  // iterate on properties , set each value 1 one  foreach (var property in type.getproperties()) {      // set value of given property on given instance     if (nodes.descendants("key").any(x => x.value == property.name)) // check if property in xml     {         // exists pick node         var node = nodes.first(x => x.descendants("key").first().value == property.name);           // set property value converting type         property.setvalue(instance,  convert.changetype(node.element("value").value,property.propertytype), null);     } }   var tempperson = (person) instance; 

i made example fiddle

it can made generic refactoring using generics.


Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -