Xpath错误具有无效令牌

use*_*355 3 c# xml xpath

我有以下C#代码:

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

当我运行我的代码时,它会引发错误,说"上面的语句有一个无效的令牌"

这些是上述陈述的值.

codeType=cbc
section="Mental"
codedesc="Injection, enzyme (eg, collagenase), palmar fascial cord (ie, 
    Dupuytren's contracture"
Run Code Online (Sandbox Code Playgroud)

Cri*_*scu 6

注意撇号(')在codedesc

你需要以某种方式逃脱它.XPath解释器将其视为字符串分隔符,并且不知道如何处理其后的其他撇号.

您可以这样做的一种方法是将字符串括在双引号而不是撇号中.

因此,您的代码可能变为:

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

(注意,在第四行,撇号(')成为双引号(\"))

虽然这种方法适用于您提供的数据,但您仍然不是100%安全:其他记录本身可能包含双引号.如果发生这种情况,我们也需要为这种情况考虑一些事情.