簡體   English   中英

for循環中的XPath求值始終從第一次迭代返回節點的值

[英]XPath evaluation in for loop always returns value for node from first Iteration

我試圖使用在for循環中調用的方法從節點中提取值。

每次調用Method時,xpath.evaluate僅計算首次傳遞給方法的原始節點。

- 示例節點

<doc>
  <str name="subcategory">xyzabc</str>
  <str name="type">QAs</str>
  <str name="id">1234</str>
</doc>

- 用於調用的循環

 ArrayList<Node> responseNodeList = parseResponse(*document as string*);   
 for(int k = 0;k<responseNodeList.size();k++){
                Result resultNode = new Result();

                resultNode.setUrl(new URL(getAttributeValue(responseNodeList.get(k),resultUrl)));
                resultNode.setId(new String(getAttributeValue(responseNodeList.get(k),resultId)));
}

- 我提取值的方法

private String getAttributeValue(final Node responseNodeUrl, String attribute) throws SearchException {
        try {   
        Node evalNode = null;
        evalNode = responseNodeUrl;

        try {
            nodelisttostr(responseNodeUrl); // This is what i am printing out the node.. where we dont have a problem
        } catch (TransformerFactoryConfigurationError e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   

        XPath xPath = XPathFactory.newInstance().newXPath();
        XPathExpression expr = null;
         expr = xPath.compile("/doc/str[@name='"+attribute+"']");  
        String result ;
        result=(String) expr.evaluate(evalNode,XPathConstants.STRING);  
        xPath.reset();
        System.out.println("++++++++"+result); //But when i print this out, it always prints the same value

        return result;
    } catch (XPathExpressionException e) {
        log.error("Error in SearchEngine:getAttributeValue:: "+e.getMessage());
        throw new SearchException(e);
    }
}

解決了..

XpathExpression總是拿起傳遞給方法的第一個節點,由於某種原因它似乎被緩存了,我把我的評估字符串改為看起來像expr = xPath.compile(".//str[@name='"+attribute+"']"); 然后評估方法現在編寫當前文檔。

謝謝你們。

如果在上面的XML上,您使用:

//doc/str/@name

你會得到:

Attribute='name="subcategory"'
Attribute='name="type"'
Attribute='name="id"'

如果在XML上面的XPath表達式中使用contains ,即

//doc/str/@name[contains(.,'e')]

然后你會得到:

Attribute='name="subcategory"'
Attribute='name="type"'

但我想你只想用你的代碼做以下事情:

改變這個:

expr = xPath.compile("/doc/str[@name='"+attribute+"']"); 

對此,即添加額外的/

expr = xPath.compile("//doc/str[@name='"+attribute+"']");

評估所有節點而不是第一個節點。

我希望這有幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM