2016-02-29 66 views
1

我有一个巨大的XML,我需要找到支付的金额。它位于2个单元远离与CELLTEXT =“量”xPath:得到父母和第二个兄弟姐妹

<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> 

这是我的代码,在那里我奋力如何构建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?

,你可以使用
+0

是正确的,它是下面的兄弟?还是应该是父母的以下兄弟姐妹? – Malin

+0

也许如果你在混合大小写拼写'Cell'并添加了缺少的'/'它会起作用吗? '以下兄弟姐妹::单元格[2]/CellText' – Andreas

+0

@Andreas你做了我的一天! 就这么简单;) – Malin

回答

4

XPath表达式如下:

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

XPathFiddle example

这将:

  • 文本等于选择CellText元素amount
  • 然后导航到它的pa租Cell元素
  • 然后导航到第2以下Cell兄弟
  • 回报从CellText子文

输出