"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Achieve Case-Insensitive contains() Functionality in XPath 1.0?

How to Achieve Case-Insensitive contains() Functionality in XPath 1.0?

Published on 2024-11-20
Browse:190

How to Achieve Case-Insensitive contains() Functionality in XPath 1.0?

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.

Release Statement This article is reprinted at: 1729588936 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

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