• 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

<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
0
mt600
Asked:
mt600
1 Solution
 
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
 
mt600Author Commented:
ok, thanks for your help.  It's good enough for me.

0

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