Home > Web Front-end > JS Tutorial > body text

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

Barbara Streisand
Release: 2024-10-23 01:17:30
Original
607 people have browsed it

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'
  )
]
Copy after login

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:

<code class="javascript">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");</code>
Copy after login

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.

The above is the detailed content of How to Achieve Case-Insensitive contains() Functionality in XPath 1.0?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!