I have a huge XML where I need to locate the amount to pay. It is located 2 cells away from the cell with CellText = 'amount'
<TableRow>
<Cell>
<RowNo>4</RowNo>
<CellColNo>1</CellColNo>
<CellText>amount</CellText>
<CellAttribute/>
</Cell>
<Cell>
<RowNo>4</RowNo>
<CellColNo>2</CellColNo>
<CellText/>
<CellAttribute/>
</Cell>
<Cell>
<RowNo>4</RowNo>
<CellColNo>3</CellColNo>
<CellText>138</CellText>
<CellAttribute/>
</Cell>
</TableRow>
Code, where I am struggling how to build the expressionString:
XPath xPath = XPathFactory.newInstance().newXPath();
String exprString =
"//TableRow/Cell[CellText='amount:']/following-sibling::cell[2]CellText/text()";
XPathExpression expr = xPath.compile(exprString);
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int j = 0; j < nodes.getLength(); j++) {
System.out.println(nodes.item(j).getNodeValue());
}
How do I create the correct exprString
?
To traverse to the next sibling, we have to use the following-sibling concept in xpath. This will allow us to traverse to the next sibling from the present sibling of the same parent. Let us try to move from the first child<h1> of parent <div> to the second <h2> as in the above image.
XPath using Preceding-Sibling So, here, in contrast to Following-Sibling, you get all the nodes that are siblings or at the same level but are before your current node. The syntax for using Preceding-Sibling is: //tagname[@attribute='value']//preceding-sibling::tagname. 1.
We can use the concept of following-sibling in xpath for identifying elements in Selenium. It identifies the siblings of the context node. The siblings should be located at the equal level of the existing node and should have the same parent.
A Sibling in Selenium Webdriver is a function used to fetch a web element which is a sibling to the parent element. If the parent element is known then the web element can be easily found or located that can use the sibling attribute of the Xpath expression in selenium webdriver.
An XPath expression that you could use is as follows:
TableRow/Cell/CellText[text()='amount']/parent::Cell/following-sibling::Cell[2]/CellText/text()
XPathFiddle example
This will:
CellText
element with text equal to amount
Cell
elementCell
siblingCellText
childOutput
138
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With