Xpath error has an Invalid Token

c#, xml, xpath

Solution

Notice the apostrophe (`'`) in `codedesc`?

You need to escape it somehow. The XPath interpreter considers it as a string delimiter and doesn't know how to treat the other apostrophe after it.

One way you can do that is by enclosing your string in double quotes instead of apostrophes.

Your code could therefore become:

var selectNode = xmlDoc.SelectSingleNode(
    "//CodeType[@name='" + codetype + "']" +
    "/Section[@title='" + section + "']" +
    "/Code[@code=\"" + code + "' and @description='" + codedesc + "\"]") 
    as XmlElement;

(note that on the fourth line, the apostrophes(`'`) became double quotes(`\"`))

While this approach works for the data you presented, you are still not 100% safe: other records could contain double quotes themselves. If that happens, we'll need to think of something for that case as well.

Problem

I have the following C# code: ``` var selectNode = xmlDoc.SelectSingleNode("//CodeType[@name='" + codetype + "']/Section[@title='" + section + "']/Code[@code='" + code + "' and @description='" + codedesc + "']") as XmlElement; ``` when I run my code it raises the error saying "the above statement has an invalid token" These are the values for the above statement. ``` codeType=cbc section="Mental" codedesc="Injection, enzyme (eg, collagenase), palmar fascial cord (ie, Dupuytren's contracture" ```

Original source