[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now


Retrieving optional nodes from an XmlDocument

Posted on 2004-10-27
Medium Priority
Last Modified: 2010-04-15
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.

Question by:mt600
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions

Accepted Solution

Razzie_ earned 750 total points
ID: 12419900
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.



Author Comment

ID: 12422262
ok, thanks for your help.  It's good enough for me.


Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…

656 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question