简体   繁体   中英

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.

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. 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 / )

So, identifySelectorKind would go a bit like this:

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. 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?

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.

If you're absolutely sure your XPath selector will always begin with / , then yes, it's fine. Note that an XPath selector doesn't have to begin with a / , but if yours always selects from the root, then it's fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM