.net - Deserialize nested XML element into class in C# -


i have following xml structure (edited brevity) have no control over.

<getvehicles>     <applicationarea>         <sender>             <blah></blah>         </sender>     </applicationarea>     <dataarea>         <error>             <blah></blah>         </error>         <vehicles>             <vehicle>                 <colour>blue</colour>                 <numofdoors>3</numofdoors>                 <bodystyle>hatchback</bodystyle>             <vehicle>         </vehicles>     </dataarea> </getvehicles> 

i have following class:

[xmlroot("getvehicles"), xmltype("vehicle")] public class vehicle {     public string colour { get; set; }     public string numofdoors { get; set; }     public string bodystyle { get; set; } } 

i want able deserialize xml single instance of vehicle class. 99% of time, xml should return single 'vehicle' element. i'm not yet dealing yet if contains multiple 'vehicle' elements inside 'vehicles' element.

unfortunately, xml data isn't being mapped class properties; being left blank upon calling deserialize method.

for completeness, here deserialize method:

private static t deserialize<t>(string data) t : class, new() {     if (string.isnullorempty(data))         return null;      var ser = new xmlserializer(typeof(t));      using (var sr = new stringreader(data))     {         return (t)ser.deserialize(sr);     } } 

i don't care other more parent elements such 'applicationarea', 'error' etc. interesting in extracting data within 'vehicle' element. how deserialize data xml?

i'm not aware of full context of problem, solution might not fit domain. 1 solution define model as:

[xmlroot("vehicle")] //<-- optional public class vehicle {     public string colour { get; set; }     public string numofdoors { get; set; }     public string bodystyle { get; set; } } 

and pass specific node deserialize method using linq xml:

var vehicle = xdocument.parse(xml)                        .descendants("vehicle")                        .first();  vehicle v = deserialize<vehicle>(vehicle.tostring());   //display contents of v  console.writeline(v.bodystyle);   //prints hatchback console.writeline(v.colour);      //prints blue console.writeline(v.numofdoors);  //prints 3 

Comments

Popular posts from this blog

Change php variable from jquery value using ajax (same page) -

Pull out data related to my apps from Android Play Store and iOS App Store -

How can I fetch data from a web server in an android application? -