aron aron - 1 year ago 69
C# Question

C# check xml node the safe way?

I have the code:

if (Element.SelectSingleNode("/rsp/merged_poco/organizations/organization/name") != null)
this.Organization = Element.SelectSingleNode("/rsp/merged_poco/organizations/organization/name").InnerText;

However there is a changes that "merged_poco" may not have "organizations". Would my code result in an error? Or just that null check suffice?
In my null check should I also check to see if "organizations" and "organization" exist?

Answer Source

Your code should suffice. You can also optimize it as the following:

XmlNode node = Element.SelectSingleNode("/rsp/merged_poco/organizations/organization/name");
if (node != null)
    this.Organization = node.InnerText;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download