2016-02-29 64 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子文

輸出