xPath:获取父级和第二个以下兄弟级 [英] xPath: get parent and second following sibling

查看:27
本文介绍了xPath:获取父级和第二个以下兄弟级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个巨大的 XML,我需要在其中找到要支付的金额.它与 CellText = 'amount'

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());
}

如何创建正确的exprString?

推荐答案

您可以使用的 XPath 表达式如下:

An XPath expression that you could use is as follows:

TableRow/Cell/CellText[text()='amount']/parent::Cell/following-sibling::Cell[2]/CellText/text()

XPathFiddle 示例

这将:

  • 选择文本等于amountCellText元素
  • 然后导航到其父 Cell 元素
  • 然后导航到它的第二个Cell兄弟
  • CellText 子元素返回文本
  • select the CellText element with text equal to amount
  • then navigate to its parent Cell element
  • then navigate to its 2nd following Cell sibling
  • return the text from the CellText child

输出

138

这篇关于xPath:获取父级和第二个以下兄弟级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆