XPath's Case-Insensitive contains()
In XSLT or other DOM-traversing applications, performing XPath queries with case-sensitive string comparisons can be limiting. However, achieving case-insensitive contains() functionality in XPath 1.0 is possible.
1. Translation-Based Method (XPath 1.0)
To match both case-sensitive and case-insensitive variations of a string, employ the translate() function:
/html/body//text()[ contains( translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'test' ) ]
This method effectively translates all uppercase letters to lowercase, enabling case-insensitive comparisons. However, it requires knowledge of the expected character set.
2. JavaScript-Assisted Dynamic XPath Generation
If manipulating the XPath expression is possible, you can use JavaScript to dynamically replace the search string with its upper and lowercase variants:
function xpathPrepare(xpath, searchString) {
return xpath.replace("$u", searchString.toUpperCase())
.replace("$l", searchString.toLowerCase())
.replace("$s", searchString.toLowerCase());
}
xp = xpathPrepare("//text()[contains(translate(., '$u', '$l'), '$s')]", "Test");
This method handles search strings with arbitrary characters, including single quotes.
Caution: These techniques may not perform optimally if complex/large string operations are involved. If possible, consider other solutions such as storing strings with known character sets or adopting XPath 2.0, which natively supports case-insensitive string comparisons.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3