[英]Identify css selector string vs XPath string
I'm working on a small querying module (in js) for html and I want to provide a generic query(selector)
function supporting both, css selectors and XPath selectors as string argument. 我正在为html编写一个小型查询模块(在js中),我想提供一个通用的query(selector)
函数,该函数同时支持css选择器和XPath选择器作为字符串参数。
Regardless of how each kind of selection is done, my problem here is how to identify whether a given string is an xpath or a css selector. 无论如何进行每种选择,这里的问题都是如何确定给定的字符串是xpath还是css选择器。 We can assume that the function would be something like this: 我们可以假设函数是这样的:
function query(selector){
selectorKind = identifySelectorKind(selector); // I want to know how to code this particular function
if(selectorKind==="css") return queryCss(selector);
if(selectorKind==="xPath") return queryXPath(selector); //Assume both functions exists and work
}
My first approach (given my limited knowledge of xPath queries) was to identify the query kind by checking if the first character is /
(here I am assuming all relevant xPath queries begin with /
) 我的第一种方法(鉴于我对xPath查询的了解有限)是通过检查第一个字符是否为/
来识别查询类型(这里我假设所有相关的xPath查询都以/
开头)
So, identifySelectorKind
would go a bit like this: 因此, identifySelectorKind
会像这样:
function identifySelectorKind(selector){
if (selector[0] === "/") return "xPath";
else return "css";
}
Note that I don't need to validate neither css nor xpath selectors, I only need an unambiguous way to differentiate them. 注意,我不需要验证css和xpath选择器,我只需要一种明确的方法来区分它们。 Would this logic be enough? 这种逻辑就足够了吗? (in other words, all xPath selectors begin with /
and no css selector begins the same way?), if not, is there a better way or some considerations I may want to know? (换句话说,所有xPath选择器都以/
开头,而没有css选择器以相同的方式开头吗?),如果不是,是否有更好的方法或我可能想知道的一些注意事项?
You can't necessarily. 不一定。 For example, *
is a valid xpath and a valid css selector, but it matches a different set of elements in each. 例如, *
是有效的xpath和有效的css选择器,但它与每个元素中的一组不同元素匹配。
If you're absolutely sure your XPath selector will always begin with /
, then yes, it's fine. 如果您完全确定XPath选择器将始终以/
开头,那么可以。 Note that an XPath selector doesn't have to begin with a /
, but if yours always selects from the root, then it's fine. 请注意,XPath选择器不必以/
开头,但是如果您总是从根目录中选择,则可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.