在Java中,如何正确确定XPath选择器是否指定属性或元素?如何确定XPath目标(返回)属性或元素?
解释这个问题:我需要从WebDriver的WebElement获取文本。元素的innerText或它的属性取决于XPath。不幸的是每个提取不同的做法(见下文),所以我必须首先确定的预期目标是什么,元素和属性:
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();
}
};
我在寻找实施targetsAttribute
,elemPart
和attrName
方法。目前我使用正则表达式的:
Pattern ATTR_PAT = Pattern.compile("^.*/@([^/]+)$");
Pattern ELEM_PAT = Pattern.compile("^(.*)/@[^/]+$");
但我觉得这种方法丑陋和非系统性。例如,它不符合attribute::
。有一些方法可以使用某些标准库或其他方法来做到这一点吗?
注:我其实是想解决类似的问题,如以下问题,只是要高一点:
How to get the value of an attribute using XPath
术语的一点:在XML和XPath中,文档树中的* elements *和attributes都是* nodes *。因此,而不是“属性或节点”,你问的是“属性或元素”。因此标识符WebElement,findElement等很好的问题。 – LarsH 2014-12-04 16:41:19