2013-07-10 75 views
1

我有在Java下面的方法:搜索一個XML文檔中的屬性與Java和XPath

private static String getAttributValue(String attribute, String xmlResponseBody) { 

    String searchAttributeValue = ""; 
    try { 
     DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); 
     Document doc = docBuilder.parse(new InputSource(new StringReader(xmlResponseBody))); 
     XPathFactory xPathFactory = XPathFactory.newInstance(); 
     XPath xpath = xPathFactory.newXPath(); 
     try { 
      XPathExpression expr = xpath.compile("@" + attribute); 
      Object result = expr.evaluate(doc, XPathConstants.NODESET); 
      NodeList nodeList = (NodeList) result; 
      Node node = nodeList.item(0); // something wrong?? 
      searchAttributeValue = node.getTextContent(); 

     } catch (XPathExpressionException e) { 
      e.printStackTrace(); 
     } 
    } catch (ParserConfigurationException pce) { 
     pce.printStackTrace(); 
    } catch (IOException ioe) { 
     ioe.printStackTrace(); 
    } catch (SAXException sae) { 
     sae.printStackTrace(); 
    } 
    return searchAttributeValue; 
} 

我一個XML文檔(參數「xmlResponseBody」)中搜索的屬性(參數「屬性」)。我想用XPath來解決這個任務。在代碼中,我對「//錯誤的東西」發表了評論,變量節點爲空。我該怎麼辦?我的代碼中有什麼錯誤?

謝謝! Marwief

回答

3

這是很難回答沒有看到示例XML(或它的一部分),但你可以搜索使用屬性

xpath.compile("//@" + attribute) 

這意味着搜索內上下文指定屬性屬性節點及其後代。你可以得到更多的信息here