C#: using xpath to find matching node

Posted on 2014-04-29
Last Modified: 2016-02-18
I have the following method which loops through the <desc> node in an xml file to find if it matches the parameter "msg".
What I need to do is ,once found retrieve the <code> from the xml. How do I do that?

        static string getCode(string msg)
            string filename = @"C:\temp\errors.xml";
            string xmlCode="";

            XmlDocument doc = new XmlDocument();
            XmlNodeList nodes = doc.SelectNodes("/edt/ce/desc");

            foreach (XmlNode node in nodes)
                if (node.InnerText.Trim().Equals(msg))
                    xmlCode = "Found";  //should be the <code> associated to the matching <desc>
                    xmlCode = "Not found";


            msg = xmlCode;

            return msg;
This is errors.xml
<edt name="errors">
            <desc>Not here</desc>
            <desc>Invalid Input </desc>
Question by:badtz7229
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
  • 3
  • 2

Expert Comment

by:deepu chandran
ID: 40031281
Please try LINQ to SQL, Below code will work

IEnumerable<XElement> xmlDocuments = from x in XElement.Load(@"d:\deepu\sample.xml").Elements("ce")
                                             select x;

        var elements = from c in xmlDocuments
                       select c;

Open in new window

LVL 52

Assisted Solution

by:Carl Tawn
Carl Tawn earned 500 total points
ID: 40031410
You can achieve what you want in one step, rather than resorting to a loop:
XmlNode node = doc.SelectSingleNode("/edt/ce[desc='" + msg + "']/code");
if (node != null)
      // found the correct node

     string code = node.InnerText;

Open in new window


Author Comment

ID: 40031882
How do I trim <desc> before inserting he parameter? Bc sometimes there's a trailing spaces in the XML file and the match won't be found
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

LVL 52

Accepted Solution

Carl Tawn earned 500 total points
ID: 40031900
The normalize-space XPath function will trim whitespace from the start and end of the string:
XmlNode node = doc.SelectSingleNode("/edt/ce[normalize-space(desc)='" + msg + "']/code");

Open in new window


Author Closing Comment

ID: 40032003
thank you, this worked successfully.

Author Comment

ID: 40032396
how do i use your solution in the event that the msg parameter contains an apostrophe?
(i.e. - Can't create Server object). This string exists in the xml

Featured Post

Use Filtering Commands to Process Files in Linux

Learn how to manipulate data with the help of various filtering commands such as `cat`, `fmt`, `pr`, and others in Linux.

Question has a verified solution.

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

I was working on a PowerPoint add-in the other day and a client asked me "can you implement a feature which processes a chart when it's pasted into a slide from another deck?". It got me wondering how to hook into built-in ribbon events in Office.
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
In this video, viewers will be given step by step instructions on adjusting mouse, pointer and cursor visibility in Microsoft Windows 10. The video seeks to educate those who are struggling with the new Windows 10 Graphical User Interface. Change Cu…
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor ( Top Charts is a view in which you can set seve…
Suggested Courses

623 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