The convertXPathToCss
function takes an XPath expression and converts it to a CSS selector, performing replacements such as removing //
separators, replacing contains
with attribute selectors, and rewriting descendant combinators. The function returns the converted CSS selector.
function convertXPathToCss(path) {
// if matched xpath is simple enough, convert it to CSS
// DIV[contains(@class, "product-tile")]/parent::*/DIV[2]//MD-CARD[contains(@class, "mat-card")]/parent::*/MD-CARD[1]
return path
.replace(/\/([a-z-]+)\[@id="(.*?)"]/ig, '/$1#$2')
.replace(/\/([^\/]+)\[contains\(@class, "(.*?)"\)]/ig, '/$1.$2')
.replace(/\/parent::[a-z-]+\/[a-z-]+\[([0-9]+)]/ig, ':nth-child($1)')
.replace(/^\/\//ig, '')
.replace(/\/\//ig, ' ')
.replace(/\//ig, ' > ');
}
/**
* Converts an XPath to a CSS selector.
*
* @param {string} path - The XPath to convert.
* @returns {string} The equivalent CSS selector.
*/
function convertXPathToCss(path) {
// Remove leading and trailing slashes
path = path.trim().replace(/^\/+|\/+$/g, '');
// Replace self-closing tags with their non-self-closing counterparts
path = path.replace(/\/([a-z-]+)\[@id="(.*?)"]/ig, '/$1#$2');
// Replace attribute contains function with CSS class
path = path.replace(/\/([^\/]+)\[contains\(@class, "(.*?)"\)]/ig, '/$1.$2');
// Replace parent axis with CSS nth-child pseudo-class
path = path.replace(/\/parent::[a-z-]+\/[a-z-]+\[([0-9]+)]/ig, ':nth-child($1)');
// Replace multiple slashes with a single space
path = path.replace(/\/+/ig,'> ');
// Remove remaining slashes and replace with spaces for readability
path = path.replace(/\//ig,'> ');
return path;
}
convertXPathToCss
path
: The XPath expression to be convertedThis function takes an XPath expression and converts it to a CSS selector.
It performs the following replacements:
//div[@id="something"]/div
-> div#something > div
//div[contains(@class, "something")]/div
-> div.something > div
//parent::* div[2]
-> nth-child(2) div
//
and intermediate //
separators//
separators with >