XQuery looking for text with 'single' quote

后端 未结 6 567
轻奢々
轻奢々 2020-12-03 18:33

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<

6条回答
  •  死守一世寂寞
    2020-12-03 19:24

    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("'", "', \"'\", '") + "', '')";!
    

提交回复
热议问题