kub1x kub1x -4 years ago 81
Java Question

How to determine whether XPath targets (returns) attribute or element?

In Java, how do you properly determine if XPath selector targets attribute or element?

To explain the issue: I need to get text from WebDriver's WebElement. Either innerText of the element or it's attribute depending on the XPath. Unfortunately each extraction is done differently (see below) so I have to determine first what the intended target is, element or attribute:

String getStringValue(String selector, WebElement context) {
if(targetsAttribute(selector) {
WebElement node = context.findElement(new By.xpath(elemPart(selector)));
return node.getAttribute(attrName(selector));
} else {
return context.findElement(new By.xpath(selector)).getText();

I'm looking for implementation of
methods. Currently I use regex's:

Pattern ATTR_PAT = Pattern.compile("^.*/@([^/]+)$");
Pattern ELEM_PAT = Pattern.compile("^(.*)/@[^/]+$");

But I find this approach ugly and non-systematic. It doesn't match
for example. Is there some way to do this using some standard library or so?

NOTE: I'm actually trying to solve similar problem as in following question, only going a bit higher:

How to get the value of an attribute using XPath

Answer Source

The lack of a node-agnostic means to address text content is a problem in many (if not all!) XPath APIs. And, as already indicated, there is no completely general way to determine in advance whether an XPath expression selects attributes or elements, as it could select both, with a disjunctive combination.

If you can rule out disjunctions (or treat each piece separately) then, heuristically, it all depends on what follows the final slash in the expression: if the remainder starts with '@' (or 'attribute::'), you're selecting an attribute; otherwise, an element. This is not bullet-proof, but from experience I've found that this is good enough in practice. Your heuristic approach is as good as any.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download