Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>EDIT:</strong> After a heavy unit testing session, and checking the <a href="http://www.w3.org/TR/xpath#exprlex" rel="noreferrer">XPath Standards</a>, I have revised my function as follows:</p> <pre><code>public static string ToXPath(string value) { const string apostrophe = "'"; const string quote = "\""; if(value.Contains(quote)) { if(value.Contains(apostrophe)) { throw new XPathException("Illegal XPath string literal."); } else { return apostrophe + value + apostrophe; } } else { return quote + value + quote; } } </code></pre> <p>It appears that XPath doesn't have a character escaping system at all, it's quite primitive really. Evidently my original code only worked by coincidence. My apologies for misleading anyone!</p> <p><strong>Original answer below for reference only - please ignore</strong></p> <p>For safety, make sure that any occurrence of all 5 predefined XML entities in your XPath string are escaped, e.g.</p> <pre><code>public static string ToXPath(string value) { return "'" + XmlEncode(value) + "'"; } public static string XmlEncode(string value) { StringBuilder text = new StringBuilder(value); text.Replace("&amp;", "&amp;amp;"); text.Replace("'", "&amp;apos;"); text.Replace(@"""", "&amp;quot;"); text.Replace("&lt;", "&amp;lt;"); text.Replace("&gt;", "&amp;gt;"); return text.ToString(); } </code></pre> <p>I have done this before and it works fine. If it doesn't work for you, maybe there is some additional context to the problem that you need to make us aware of.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload