Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

C#: using xpath to find matching node

Posted on 2014-04-29
6
Medium Priority
?
867 Views
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();
            doc.Load(filename);
            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>
                else
                    xmlCode = "Not found";

            }

            msg = xmlCode;

            return msg;
        }
            
            
This is errors.xml
<edt name="errors">
      <ce>
            <code>1111</code>
            <desc>Not here</desc>
      </ce>
      <ce>
            <code>2222</code>
            <desc>Invalid Input </desc>
      </ce>
</edt>
0
Comment
Question by:badtz7229
[X]
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
6 Comments
 
LVL 8

Expert Comment

by:deepu chandran
ID: 40031281
Hi,
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
                       where
                           c.Element("desc").Value.Contains("Not")
                       select c;

Open in new window


Thanks
Deepu
0
 
LVL 52

Assisted Solution

by:Carl Tawn
Carl Tawn earned 2000 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

0
 

Author Comment

by:badtz7229
ID: 40031882
@carl
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
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 52

Accepted Solution

by:
Carl Tawn earned 2000 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

0
 

Author Closing Comment

by:badtz7229
ID: 40032003
thank you, this worked successfully.
0
 

Author Comment

by:badtz7229
ID: 40032396
@carl
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
0

Featured Post

RHCE - Red Hat OpenStack Prep Course

This course will provide in-depth training so that students who currently hold the EX200 & EX210 certifications can sit for the EX310 exam. Students will learn how to deploy & manage a full Red Hat environment with Ceph block storage, & integrate Ceph into other OpenStack service

Question has a verified solution.

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

The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This course is ideal for IT System Administrators working with VMware vSphere and its associated products in their company infrastructure. This course teaches you how to install and maintain this virtualization technology to store data, prevent vuln…
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …
Suggested Courses

688 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