Link to home
Start Free TrialLog in
Avatar of tesmc
tesmcFlag for United States of America

asked on

C#: using xpath to find matching node

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>
Avatar of deepu chandran
deepu chandran
Flag of Germany image

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
SOLUTION
Avatar of Carl Tawn
Carl Tawn
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of tesmc

ASKER

@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
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of tesmc

ASKER

thank you, this worked successfully.
Avatar of tesmc

ASKER

@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