Handling Apostrophe (single-quote) in XPath expressions in .NET
October 4, 2007
If you are playing with XML using .NET libraries, then you might be familiar with below mentioned exception:
System.Xml.XPath.XPathException: ‘objOfXmlDocument[@attribute={value containing single-quote}]’ has an invalid token.
If you are looking for a patch for the above mentioned problem, then you are at the right place.
Sample xml text: //test.xml
<?xml version=”1.0″ encoding=”utf-8″ ?>
<root>
<emp fname=”Vaibhav” lname=”Gaikwad” />
<emp fname=”Lavina” lname=”D’cunha” />
</root>
//code to access the test.xml
class Program
{
static void Main(string[] args) {
XmlDocument doc = new XmlDocument();
doc.Load(“test.xml”);
string ln = “D’cunha”;
// This fails :(( resulting in XPath exception.
XmlNode n = doc.SelectSingleNode(“/root/emp[@lname=’ “+ ln +” ‘]”);
}
}
So, the issue is due the single-quote inside the XPath expression.
We try to resolve it using the “concat” function of XSL, and this is the helper function:
public static string GetXPathString(string input) {
string[] fragments = input.Split(new char[] { ‘\” });
string result = “”;
result += “concat(””;
for (int i = 0; i < fragments.Length; i++)
{
result += “, ‘” + fragments[i] + “‘”;
if (i < fragments.Length – 1)
{
result += “, \”‘\””;
}
}
result += “)”;
return result;
}
And here is how you modify the above code so as to use our new function:
// remember to remove the single-quotes after = and ]
XmlNode n = doc.SelectSingleNode(“/root/emp[@lname=” + GetXPathString(ln) + “]”);
So its all done and the day is saved.
-Bugs!