aron aron - 1 month ago 12
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

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;
Comments