Reputation:
i have the following method in java:
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;
}
I search an attribute (parameter "attribute") in a xml document (parameter "xmlResponseBody"). I would like to use XPath to solve this task. At the code, which i have comment with "// something wrong", the variable node is null. What should i do? What is the mistake in my code?
Thanks ! Marwief
Upvotes: 1
Views: 475
Reputation: 2801
It is hard to answer this without seeing the sample xml(or part of it), but you can search for an attribute using
xpath.compile("//@" + attribute)
It means search for attribute named attribute inside context node and its descendants. You can get more information here.
Upvotes: 2