• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 877
  • Last Modified:

C#: how to use xpath to escape a token

how do i use the below:

XmlNode node = doc.SelectSingleNode("/edt/ce[normalize-space(desc)='" + msg + "']/code");

in the event that the msg parameter contains an apostrophe or other special characters (since it is a string). (i.e. - Can't create Server object). This string exists in the xml . the <desc> tag does contain  special characters as well (since it's a string).

how do i escape special grammar characters like commas ,colon, parenthesis,  dash, slash , underscore)
0
badtz7229
Asked:
badtz7229
  • 3
  • 2
1 Solution
 
zc2Commented:
Replace the invalid characters in the msg with entities, something like
msg = msg.replace( "'", "&#x27;" )
0
 
badtz7229Author Commented:
if i use a replace it won't find it in the xml then.
for example
msg =  Can't create Server object

and my xml file contains

<edt name="errors">
      <ce>
            <code>111</code>
            <desc>Not here</desc>
      </ce>
      <ce>
            <code>222</code>
            <desc>Can't create Server object </desc>
      </ce>
</edt>
0
 
zc2Commented:
You are right, entity does not work.
If the apostrophe only could be in the string, then we could avoid using it in the xpath:
XmlNode node = doc.SelectSingleNode("/edt/ce[normalize-space(desc)=\"" + msg + "\"]/code");
0
 
badtz7229Author Commented:
@ zc2
your last comment worked successfully.
thanks.
0
 
zc2Commented:
This should work even if the search string contains both single and double quote characters:
            msg = "concat('" + msg.Replace( "'", "',\"'\",'" ) + "')";
            XmlNode node = doc.SelectSingleNode("/edt/ce[normalize-space(desc)=" + msg + "]/code");

Open in new window

0

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!

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now