tesmc
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/d esc");
foreach (XmlNode node in nodes)
{
if (node.InnerText.Trim().Equ als(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>
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/d
foreach (XmlNode node in nodes)
{
if (node.InnerText.Trim().Equ
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>
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
thank you, this worked successfully.
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
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
Please try LINQ to SQL, Below code will work
Open in new window
Thanks
Deepu