c# - XML - Check for existence of a specific node -


i don't know why i'm having trouble this, i'm hoping can me pointed in right direction.

i have these few lines of code :

var xdoc = new xmldocument(); xdoc.loadxml(xelementvar.tostring());  if (xdoc.childnodes[0].haschildnodes) {     (int = 0; < xdoc.childnodes[0].childnodes.count; i++)     {         var sformatid = xdoc.childnodes[0].childnodes[i].attributes["formatid"].value;         // stuff     }     // more stuff } 

the problem xdoc i'm getting doesn't have formatid node, end getting null reference exception, although 99% of time works fine.

my question :

how can check if formatid node exists before try read value out of it?

if node not exist, returns null.

if (xdoc.childnodes[0].childnode[i].attributes["formatid"] != null)     sformatid = xdoc.childnodes[0].childnodes[i].attributes["formatid"].value; 

of can shortcut way

var sformatid = xdoc.childnodes[0].childnodes[i].attributes["formatid"] != null ? xdoc.childnodes[0].childnodes[i].attributes["formatid"].value : "formatid not exist"; 

the format this.

var variable = condition ? : b; 

this saying if condition true, variable = a, otherwise, variable = b.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -