In c-sharp, while using XPath expression to select nodes from XML Document like
string busname="Domino's Pizza";
xoEle = (XmlElement)xoDoc.DocumentElement.SelectSingleNode("//Review[RestaurantName='"
+ busname + "']");
would result in error such as
System.Xml.XPath.XPathException: '//Review[RestaurantName='Domino's Pizza']' has an invalid token.
This is due to single quote (Apostrophe) on variable used on XPath expressions.
Above problem (i.e) to escape single quote (Apostrophe) can be resolved by using XPATH concat function as
//Review[RestaurantName=concat("Domino","'","s Pizza")]Hence below "ParseXpathString" function can be used to parse single quote on XPATH in C# .Net.
"ParseXpathString" function would create concat function programmatically.
private static string ParseXpathString(string input)
{
string ret = "";
if (input.Contains("'"))
{
string[] inputstrs = input.Split('\'');
foreach (string inputstr in inputstrs)
{
if (ret != "")
ret += ",\"'\",";
ret += "\"" + inputstr + "\"";
}
ret = "concat(" + ret + ")";
}
else
{
ret = "'" + input + "'";
}
return ret;
}
This function as be used as
xoEle = (XmlElement)xoDoc.DocumentElement.SelectSingleNode("//Review[RestaurantName="
+ ParseXpathString(busname) + "]");
Hey, this was very useful. I just wanted to point out that this still breaks if you're searching for something that has both single and double quotes. I have modified the function to support this. If you want it let me know gsacavdm@hotmail.com
Thanks, I didnt know double-quotes were even possible, and yep, ought to be optimized for it (untested): SelectSingleNode("//Review[RestaurantName=" + XPathQuote(busname) + "]" public static string XPathQuote(string value) { return string.IsNullOrEmpty(value) ? "''" : (value.Contains('\'') ? "concat('" + string.Join("', \"'\", '", value.Split('\'')) + "')" : "'" + value + "'"); }
Hi, The post was very helpful. Thanks for sharing. Thanks Sohel