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

<name><firstname>a</firstname><surname>b</surname></name>

or

<name><firstname>a</firstname><surname>c</surname><middlename>b</middlename></name>

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.

Cheers
mt600Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Razzie_Commented:
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
else
   // 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.

Cheers,

Razzie
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
mt600Author Commented:
ok, thanks for your help.  It's good enough for me.

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.