mercoledì 9 maggio 2007

How to escape apostrophes in XPath / .net

Yesterday I found something interesting: there isn't a correct way to escape string literals in XPath queries.

Example:

galleryDocument.SelectSingleNode("//photo[filename='" + photoFileName + "']");

This line raises an exception if photoFileName contains an apostrophe. Neither ' nor \' nor '' work as an escape sequence - the XPath specifications do not handle that. So, how do we deal with it?

The answer is a small routine that relies on the concat XPath function:

public static string EscapeApostropheForXPathParameter(string parameter)
{
if (!parameter.Contains("'")) return "'" + parameter + "'";

string[] parts = parameter.Split('\'');

string result = String.Empty;
foreach (string part in parts)
result += ", \"'\", '" + part + "'";

return "concat(" + result.Substring(7) + ")";
}

This routine basically maps the string "foo'bar" into concat('foo', "'", 'bar'). Please note the different kind of quotes around the apostrophe. Nice to know, huh? :-)

Nessun commento: