2013-07-10 1 views
1

i ont la méthode suivante en java:Rechercher un attribut dans un document XML avec Java et 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; 
} 

Je recherche un attribut (paramètre "attribut") dans un document XML (paramètre "xmlResponseBody"). Je voudrais utiliser XPath pour résoudre cette tâche. Au code, que j'ai commenter avec "// quelque chose de mal", le noeud de la variable est nul. Que devrais-je faire? Quelle est l'erreur dans mon code?

Merci! Marwief

Répondre

3

Il est difficile de répondre à cela sans voir l'exemple de fichier XML (ou une partie de celui-ci), mais vous pouvez rechercher un attribut à l'aide

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

Cela signifie recherche d'attribut nommé attribut contexte intérieur nœud et ses descendants. Vous pouvez obtenir plus d'informations here.

Questions connexes