Note that there are some explanatory texts on larger screens.

plurals
  1. POc# choosing class properties with a variable?
    text
    copied!<p>I'm adding functionality to one of our existing (but broken) systems. It grabs an XML file from a web service, parses it and then does some stuff before packing it back into our database.</p> <p>the previous developer (who has now left) left me this little gem:</p> <p><a href="http://dl.getdropbox.com/u/109069/wut.GIF" rel="nofollow noreferrer">http://dl.getdropbox.com/u/109069/wut.GIF</a></p> <p>and I wonder if there's a way round this?</p> <p>Can I loop through each node and assign to the wo object by its name?</p> <p>something like this (pseudo code):</p> <pre><code> foreach XmlNode xn in WorkorderNodeTree { //find out the property name of the current node //match to the property in the workorder class //set the value equal wo.&lt;xn.name&gt; = xn.innertext } </code></pre> <p>Now the only thing I found which gets close is this (from the interweb):</p> <pre><code> foreach (XmlNode xl in myXML) { object o = Assembly.GetExecutingAssembly().CreateInstance("Workorder", true); Type t = xl.Name.GetType(); PropertyInfo pi = t.GetProperty(xl.Name); pi.SetValue(o, xl.InnerText, null); } </code></pre> <p>but it returns a null reference exception on o. I am a little confused, any tips?</p> <p>I presume to do this, I need to use reflection or generics, but I've never hit upon these things before - can anyone advise anything which might point me in the right direction or at least try to explain reflection?</p> <p>Many thanks all, apologies for the hideously long post!</p> <p>EDIT: </p> <p>Thanks, Very deep and sincere thanks go to Fredrik and Rytmis - both of you are white knights in my drab office environment. Rytmis' code edits have solved the issue but I have learned much in this hour or so - Thanks guys, really appreciate it.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload