2011-05-13 35 views
5

我試圖解析來自USGS的一些XML。XPathExpression未在正確的上下文中評估?

Here's an example

的 「parameterCd」 參數列出了3項數據,我想回去。我可能會也可能不會全部回來。

我在使用javax庫的Android上執行此操作。

在我的代碼,我最初檢索0-3 NS1:時間序列節點。這工作正常。然後,我想要在單個timeSeries節點的上下文中檢索ns1:variable和ns1:values節點。

所以在我下面的代碼,我有:

expr = xpath.compile("//ns1:variable"); 
NodeList variableNodes = (NodeList) expr.evaluate(timeSeriesNode, XPathConstants.NODESET); 

我希望只拿回一個節點,因爲評估應在我傳遞在單timeSeriesNode的背景下發生的(根據documentation)。但是,它會返回文檔的所有ns1:variable節點,但是。

我錯過了什麼嗎?

下面是相關的部分...

XPathFactory factory = XPathFactory.newInstance(); 
XPath xpath = factory.newXPath(); 
xpath.setNamespaceContext(new InstantaneousValuesNamespaceContext()); 
XPathExpression expr; 
NodeList timeSeriesNodes = null; 
InputStream is = new ByteArrayInputStream(sourceXml.getBytes()); 
try { 
    expr = xpath.compile("//ns1:timeSeries"); 
    timeSeriesNodes = (NodeList) expr.evaluate(new InputSource(is), XPathConstants.NODESET); 

    for(int timeSeriesIndex = 0;timeSeriesIndex < timeSeriesNodes.getLength(); timeSeriesIndex++){ 
     Node timeSeriesNode = timeSeriesNodes.item(timeSeriesIndex); 
     expr = xpath.compile("//ns1:variable"); 
     NodeList variableNodes = (NodeList) expr.evaluate(timeSeriesNode, XPathConstants.NODESET); 

     // Problem here. I've got all the variables, not the individual one I want. 
     for(int variableIndex = 0; variableIndex < variableNodes.getLength(); variableIndex++){ 
      Node variableNode = variableNodes.item(variableIndex); 
      expr = xpath.compile("//ns1:valueType"); 
      NodeList valueTypeNodes = (NodeList) expr.evaluate(variableNode, XPathConstants.NODESET); 
     } 
    } 
} catch (XPathExpressionException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

回答

5

嘗試改變

//ns1:variable 

.//ns1:variable 

即使作爲文件說,該表達的範圍內評估當前節點,//是特殊的(除非修改)始終爲表示'從根目錄搜索整個文檔'。通過放入.,你可以強制你想要的含義,「從這個點向下搜索整棵樹」。

+0

哇,我覺得很傻。謝謝。 – Pete 2011-05-13 22:46:02

+0

爲什麼它可以使用起始點而不是沒有起始點? – Stephan 2015-04-22 07:53:22

+0

@Stephan是否可以編輯幫助? – AakashM 2015-04-22 09:19:50

相關問題