不区分大小写的 XPath contains() 可能吗? [英] Case insensitive XPath contains() possible?

查看:29
本文介绍了不区分大小写的 XPath contains() 可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行我的 DOM 的所有文本节点并检查 nodeValue 是否包含某个字符串.

I'm running over all textnodes of my DOM and check if the nodeValue contains a certain string.

/html/body//text()[contains(.,'test')]

这是区分大小写的.但是,我也想捕获 TestTESTTest.使用 XPath(在 JavaScript 中)可以实现吗?

This is case sensitive. However, I also want to catch Test, TEST or TesT. Is that possible with XPath (in JavaScript)?

推荐答案

这适用于 XPath 1.0.如果您的环境支持 XPath 2.0,请参阅此处.

This is for XPath 1.0. If your environment supports XPath 2.0, see here.

是的.可能,但并不美丽.

Yes. Possible, but not beautiful.

/html/body//text()[
  contains(
    translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'),
    'test'
  )
]

这适用于预先知道字母表的搜索字符串.添加您希望看到的任何重音字符.

This would work for search strings where the alphabet is known beforehand. Add any accented characters you expect to see.

如果可以,用其他方式标记您感兴趣的文本,例如在构建 HTML 时将其包含在具有特定类的 <span> 中.与元素文本中的子字符串相比,使用 XPath 更容易定位此类内容.

If you can, mark the text that interests you with some other means, like enclosing it in a <span> that has a certain class while building the HTML. Such things are much easier to locate with XPath than substrings in the element text.

如果这不是一个选项,您可以让 JavaScript(或您用来执行 XPath 的任何其他宿主语言)帮助您构建动态 XPath 表达式:

If that's not an option, you can let JavaScript (or any other host language that you are using to execute XPath) help you with building an dynamic XPath expression:

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");
// -> "//text()[contains(translate(., 'TEST', 'test'), 'test')]"

(帽子提示 @KirillPolishchuk 的回答 - 当然你只需要翻译那些你想要的字符实际上搜索.)

(Hat tip to @KirillPolishchuk's answer - of course you only need to translate those characters you're actually searching for.)

这种方法适用于任何搜索字符串,无需事先了解字母表,这是一个很大的优势.

This approach would work for any search string whatsoever, without requiring prior knowledge of the alphabet, which is a big plus.

当搜索字符串可以包含单引号时,上述两种方法都会失败,在这种情况下,事情会变得更加复杂.

Both of the methods above fail when search strings can contain single quotes, in which case things get more complicated.

这篇关于不区分大小写的 XPath contains() 可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆