Escaping Strings in XPath 1.0
XML / XPath / XSLT c++ xpath
Published: 2008-06-03
Escaping Strings in XPath 1.0

XPath is a language for selecting nodes from an XML document. XPath is used extensively in XSLT and other XML technologies. I also vastly prefer using XPath (e.g. with XPathNavigator) over the XML DOM when manipulating XML in a non-streaming fashion.

In XPath, strings must be delimited by either single or double quotes. Given a quote character used to delimit a string, one can’t represent that same quote character within the string. This means that if you decide to use single quotes to delimit your XPath string, you couldn’t represent the string O’Reilly; use double quotes, and you can’t represent “Hello”.

However, given a quote delimiter, you can represent the other quote character. We can use this observation along with the concat XPath function to devise a general quoting rule for XPath strings. It’s easiest to show this via a series of examples:

Original String Quoted XPath String
a 'a' (or "a")
O'Reilly "O'Reilly"
"Hello" '"Hello"'
"Hello, Mr. O'Reilly" concat('"Hello, Mr. O', "'Reilly", '"')

Below is a piece of C++ code which implements these quotation rules:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
std::string QuoteXPathString(const std::string& xpath)
{
    // If we don't have any single or double-quote characters, quote the
    // expression in single quotes.
    std::string::size_type pos = xpath.find_first_of("'\"");
    if (pos == std::string::npos)
        return "'" + xpath + "'";

    // If we cannot find the alternate quotation character, quote the
    // expression in the alternate quotation character.
    char chOther = (xpath[pos] == '"' ? '\'' : '"');
    pos = xpath.find(chOther, pos + 1);
    if (pos == std::string::npos)
        return chOther + xpath + chOther;

    // The string has both quotation characters. We need to use concat()
    // to form the string.
    std::stringstream ss;
    ss << "concat("
       << chOther
       << xpath.substr(0, pos)
       << chOther;
    do {
        chOther = (xpath[pos] == '"' ? '\'' : '"');
        std::string::size_type pos2 = xpath.find(chOther, pos + 1);
        ss << ','
           << chOther
           << xpath.substr(pos, pos2  pos)
           << chOther;
        pos = pos2;
    } while (pos != std::string::npos);
    ss << ")";

    return ss.str();
}

Usage looks like:

1
2
std::string lastName = ; // May come from user input
std::string xpath = "//Customer[LastName = " + QuoteXPathString(lastName) + "]";