• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 240
  • Last Modified:

Retrieving optional nodes from an XmlDocument

I have some Xml documents which i want to parse into C#, but they have many optional nodes that may or may not be there.
For example




How can i retrieve these single nodes quickly from Xml using c#?

I have been using .SelectSingleNode("//name/firstname") etc but these throw an exception if the node is not there.  Exceptions are pretty computationally expensive so i want to find a better way of finding out if a node exists in an xml document.

In summary, if i have an xml document which has lots of optional nodes, what is the best way to program my C# to use the values in these nodes if they exist.

1 Solution
The easiest way to do is to check if the node is null after you select it:

XmlNode node = xmlDoc.SelectSingleNode("//name/firstname");
if(node != null)
   // The node exists, do something with it
   // The node does not exist, do something else

You could always loop through your complete XML using recursion, but it really depends on the situation if you need that.


mt600Author Commented:
ok, thanks for your help.  It's good enough for me.


Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now