XQuery looking for text with 'single' quote

escaping, xpath

Solution

Here's a hackaround (Thanks Dimitre Novatchev) that will allow me to search for any text in xpaths, whether it contains single or double quotes. Implemented in JS, but could be easily translated to other languages

function cleanStringForXpath(str)  {
    var parts = str.match(/[^'"]+|['"]/g);
    parts = parts.map(function(part){
        if (part === "'")  {
            return '"\'"'; // output "'"
        }

        if (part === '"') {
            return "'\"'"; // output '"'
        }
        return "'" + part + "'";
    });
    return "concat(" + parts.join(",") + ")";
}

If I'm looking for `I'm reading "Harry Potter"` I could do the following

var xpathString = cleanStringForXpath( "I'm reading \"Harry Potter\"" );
$x("//*[text()="+ xpathString +"]");
// The xpath created becomes 
// //*[text()=concat('I',"'",'m reading ','"','Harry Potter','"')]

Here's a (much shorter) Java version. It's exactly the same as JavaScript, if you remove type information. Thanks to https://stackoverflow.com/users/1850609/acdcjunior

String escapedText = "concat('"+originalText.replace("'", "', \"'\", '") + "', '')";!

Problem

I can't figure out how to search for text containing single quotes using XPATHs. For example, I've added a quote to the title of this question. The following line ``` $x("//*[text()='XQuery looking for text with 'single' quote']") ``` Returns an empty array. However, if I try the following ``` $x("//*[text()=\"XQuery looking for text with 'single' quote\"]") ``` It does return the link for the title of the page, but I would like to be able to accept both single and double quotes in there, so I can't just tailor it for the single/double quote. You can try it in chrome's or firebug's console on this page.

Original source